0
votes

Suppose I have the following trait:

trait Foo[T] {
  def returnMyself: T
}

Is there any way that would tell scala that any class that extends Foo does so with itself as the generic parameter?

Basically, what I want to achieve is being able to write

class Bar extends Foo {
  override def returnMyself: Bar = this
}

without having to explicitly write

class Bar extends Foo[Bar]

I hope I've made myself clear

1
To clarify: is it required that returnMyself must yield the same instance? Or may it be another instance of the same class? - Owen

1 Answers

0
votes

You should be able to do it using self types:

trait Foo { self =>
  def returnMyself: self.type
}

class Bar extends Foo {
  override def returnMyself = this
}