scala – 单例对象的类参数(泛型)
发布时间:2020-12-16 09:49:59 所属栏目:安全 来源:网络整理
导读:在 his course on Coursera,Martin Odesrky教授在关于多态性和参数化类的讲座中使用链表作为示例: package week4trait 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
在
his course on Coursera,Martin Odesrky教授在关于多态性和参数化类的讲座中使用链表作为示例:
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类的实例化,新的Nil(). 如何将Nil定义为对象而不是Scala类,并使其符合参数化类型List [T]? 我想在下面的代码行中引用Nil对象(没有实例化),并使其具有正确的类型 new Cons("A",Nil))) 解决方法
在实际的Scala库(
List.scala)中,这是如何完成的,
case object Nil extends List[Nothing] { ... 可能在课堂上他想避免引入Nothing,这就是type at the bottom of Scala’s type lattice. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |