如何在sbt中使用自己的类型而不是scala标准类型?

时间:2017-07-13 23:13:18

标签: scala sbt read-eval-print-loop

我有以下学习内容。

package learning.laziness

sealed trait Stream[+A] {
  def headOption: Option[A] = this match {
    case Empty => None
    case Cons(h, _) => Some(h())
  }

  def toList: List[A] = this match {
    case Empty => List.empty
    case Cons(h,t) => h()::t().toList
  }
}
case object Empty extends Stream[Nothing]
case class Cons[A](head: () => A, tail: () => Stream[A]) extends Stream[A]

object Stream {
  def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
    lazy val head = hd
    lazy val tail = tl
    Cons(() => head, () => tail)
  }
  def empty[A]: Stream[A] = Empty
  def apply[A](as: A*): Stream[A] =
    if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))
}

当我通过sbt console加载REPL并输入例如

  • Stream(1,2)
    • res0: scala.collection.immutable.Stream[Int] = Stream(1, ?)
  • Stream.apply(1,2)
    • res1: scala.collection.immutable.Stream[Int] = Stream(1, ?)
  • Stream.cons(1, Stream.cons(2, Stream.empty))
    • res2: Stream.Cons[Int] = Stream(1, ?)

它在两个第一种情况下使用来自scala.collection.immutable的Stream而不是我的。我怎样才能让sbt只使用我的?

1 个答案:

答案 0 :(得分:3)

SBT控制台中,在尝试使用它之前导入您的类:

scala> import learning.laziness.Stream
scala> Stream(1, 2)
scala> //etc.

您的Stream班级代码必须位于 SBT 源文件夹下(默认情况下,相对于项目根目录,这将是src/main/scala,或者在 SBT scalaSource in Compile指令指定的自定义源目录中 - SBT 将无法找到并编译它。由于您提供的代码位于learning.laziness包中,因此Stream.scala源文件的默认位置必须为src/main/scala/learning/laziness。一旦 SBT 知道在哪里找到你的文件,你就可以了。

相关问题