Scala:特征中的方法不能使用伴随对象中的方法

问题描述 投票:0回答:1

[当我尝试编译以下内容时,我得到:取放方法定义的“未找到:值错误”和“未找到:值空”。

以某种方式特征无法“看到”伴随对象?

如果有问题,我正在使用IntelliJ IDEA。

import scala.annotation.tailrec

object Run extends App {
  sealed trait StreamRed[+A] {
    def headOption: Option[A] = this match {
      case Empty => None
      case Cons(h,t) => Some(h())
    }

    def toList: List[A] = {
      @tailrec
      def toListRec(stream: StreamRed[A], accumulated: List[A]): List[A] = this match {
        case Cons(h,t) => toListRec(t(), h()::accumulated)
        case _ => accumulated
      }
      toListRec(this, List()).reverse
    }

    def take(n: Int): StreamRed[A] = this match {
      case Cons(h, t) if n > 1 => cons(h(), t().take(n - 1))
      case Cons(h, _) if n == 1 => cons(h(), empty)
      case _ => empty
    }

    @tailrec
    def drop(n: Int): StreamRed[A] = this match {
      case Cons(_,t) if n > 0 => t().drop(n-1)
      case _ => empty
    }

  }
  case object Empty extends StreamRed[Nothing]
  case class Cons[+A](h: () => A, t: () => StreamRed[A]) extends StreamRed[A]

  object StreamRed {
    def cons[A](hd: => A, tl: => StreamRed[A]): StreamRed[A] = {
      lazy val head = hd
      lazy val tail = tl
      Cons(() => head, () => tail)
    }

    def empty[A]: StreamRed[A] = Empty

    def apply[A](as: A*): StreamRed[A] =
      if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))
  }
}
scala companion-object
1个回答
0
投票

同伴可以看到彼此的成员,因为访问修饰符不是问题。

class A {
  private def foo: Unit = ()

  A.bar 
}
object A {
  private def bar: Unit = ()

  (new A).foo
}

与之相反可以

class A {
  private def foo: Unit = ()

  B.bar 
}
object B {
  private def bar: Unit = ()

  (new A).foo
}

(但是如果将private替换为private[this],则前者也将不起作用。]

但这并不意味着名称空间会自动导入。

class A {
  private def foo: Unit = ()

  import A._
  bar
}
object A {
  private def bar: Unit = ()

  val a = new A
  import a._
  foo
}

与之相反可以

class A {
  private def foo: Unit = ()

  bar
}
object A {
  private def bar: Unit = ()

  foo
}

无论如何,方法必须知道其this

© www.soinside.com 2019 - 2024. All rights reserved.