how to extend Stream by implementing tailDefined

2019-08-14 18:48发布

问题:

I'd like to extend scala.Stream. When I try, it tells me I can't, because I don't have the required method tailDefined.

class S[T](s:Stream[T]) extends Stream[T] {

}

When I try this, it tells me tailDefined is protected:

class S[T](s:Stream[T]) extends Stream[T] {
  def tailDefined = s.tailDefined
}

How do I get around this limitation and implement an extension of Stream?

回答1:

If you want to "add new methods" to Stream, use implicit classes:

implicit class S[T](s:Stream[T]) {
  def method1 = ...
}

val s: Stream[Int] = ...
s.method1