Scala an abstract type representing a subclass type

I am looking for a way to define a method that returns a type T, where T = the type of the subclass.

I know I can do this using abstract types, but I don't like the overhead of having to override T for each subclass.

Code example:

object Helper { def help[A <: MyClass](cls: A): Option[A] = { cls.foo() map { _.asInstanceOf[A] } } } class MyClass { type T <: MyClass def foo(): Option[T] = Some(this.asInstanceOf[T]) } class ChildClass extends MyClass { type T = ChildClass } 

Perhaps a new language feature made it easier? Or can I somehow use this.type? It is important for me that I can define a helper class that can call foo this way.

+6
source share
3 answers

If you always return this , then you really can have a return type of this.type . Or have you tried it already?

this.type especially useful, for example, when you want to associate calls with the same object or provide a static guarantee that you will return the same object (and not a copy). For example, Buffer in Scala has an add operation :+ , which returns Buffer[A] and += , which returns this.type . The first duplicates a mutable sequence; the latter ensures that you update the source object.

+3
source

To answer the answer of Jean-Phillippe, who wrote it when I write, here is the code:

 trait SomeTrait { def foo: this.type = this } class UsesTrait extends SomeTrait object Main { def main(args: Array[String]) { println((new UsesTrait).foo) // prints UsesTrait@ <hash value> } } 
+2
source

I found the following idiom useful:

 class MyClass[T] { self: T => def foo(): Option[T] = Some(this) } class ChildClass extends MyClass[ChildClass] new ChildClass().foo() //--> Option[ChildClass] = Some( ChildClass@2487b1 ) 
+2
source

Source: https://habr.com/ru/post/893850/


All Articles