tribbloid
tribbloid

Reputation: 3838

In Scala, How to define a class method that only takes subclass-type argument?

I've tried

def function[T <: this.type](parameter: T)

but it doesn't work.

This should just be a simple problem and its too heavyweight to define a CanBuildFrom and import it everytime before using the function

Upvotes: 0

Views: 836

Answers (1)

som-snytt
som-snytt

Reputation: 39577

The standard collections encode it with a type param.

scala> abstract class X[Repr <: X[Repr]] { def f(r: Repr) }
defined class X

scala> class Y extends X[Y] { def f(y: Y) = ??? }
defined class Y

scala> val y = new Y
y: Y = Y@6ae40994

scala> y f y
scala.NotImplementedError: an implementation is missing
  at scala.Predef$.$qmark$qmark$qmark(Predef.scala:225)
  at Y.f(<console>:8)
  ... 33 elided

Upvotes: 1

Related Questions