在 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/