trait Stream[+A] {
def toList: List[A] = this match{
case Empty => Nil
case Cons(h,t) => h() :: t().toList
}
def headOption:Option[A] = this match{
case Empty => None
case Cons(h,t) => Some(h())
}
}
case object Empty extends Stream[Nothing]
case class Cons[+A](h: ()=>A, t : ()=>Stream[A]) extends Stream[A]
object Stream{
def cons[A](h: =>A, t : =>Stream[A]): Stream[A]= {
lazy val head = h
lazy val tail = t
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: _*))
}
如图,照抄了一个Steam的实现,但是我的疑惑是toList方法,他不应该放在伴生对象里吗?一开始toList我用的虚函数,但我看headOption能用模式匹配,我就试了试,也可以,所以toList怎么实现多态的?我自己有点晕。
伴生对象有些类似于java里面静态工厂类