scala的类和伴生对象的一些疑惑

  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怎么实现多态的?我自己有点晕。

阅读 3.3k
1 个回答

伴生对象有些类似于java里面静态工厂类

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进