scala - 单例对象的类参数(泛型)

标签 scala

his course on Coursera ,Martin Odesky教授在关于多态和参数化类的讲座中以链表为例:

package week4

trait List[T] {
  def isEmpty: Boolean
  def head: T
  def tail: List[T]
}
class Cons[T](val head: T, val tail: List[T]) extends List[T] {
  def isEmpty = false
}
class Nil[T] extends List[T] {
  def isEmpty = true
  def head = throw new NoSuchElementException("Nil.head")
  def tail = throw new NoSuchElementException("Nil.tail")
}
object Main extends App {
  def main(args: Array[String]) {
    val lst = new Cons("A", new Cons("B", new Cons("C", new Nil())))
  }
}

困扰我的是最后几行中 Nil 类的实例化,new Nil() .

如何将 Nil 定义为 object而不是作为 Scala 类,并使其符合参数化类型 List[T] ?

我想在下面的代码行(没有实例化)中引用对象 Nil,并使其具有正确的类型
new Cons("A", new Cons("B", new Cons("C", Nil)))

最佳答案

在实际的 Scala 库 ( List.scala ) 中,这是如何完成的,

case object Nil extends List[Nothing] { ...

可能是在类里面他想避免介绍Nothing ,这是 type at the bottom of Scala's type lattice .

关于scala - 单例对象的类参数(泛型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16001274/

相关文章:

scala - Akka 超时启动事件处理程序

scala - Scala 中的隐式函数无法按预期工作

java - 编译错误 : Cannot us a method returning CompetionStage as a Handler for requests

java - 如何在 Scala 中匿名实现 Java 接口(interface)?

scala - 过滤字符串序列直到在scala中找到键的功能方法

scala - docker akka和scala,应用程序无故启动和停止

scala - 使用Spark的间歇性超时异常

scala - 懒惰的 val vs. Scala 中递归流的 val

scala - Scala 和 Jython 的互操作性

scala - 名称/惰性函数的重复参数