簡體   English   中英

Scala:trait 中的方法不能使用來自伴生對象的方法

[英]Scala: methods in trait can't use methods from companion object

當我嘗試編譯以下內容時,我得到:“未找到:值 cons”和“未找到:值為空”的 take 和 drop 方法定義。

不知何故,特征沒有“看到”伴隨對象?

我正在使用 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: _*))
  }
}

從訪問修飾符不是問題的意義上說,同伴可以看到彼此的成員。

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[this]替換private ,前者也不起作用。)

但這並不意味着名稱空間是自動導入的。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM