开发者

Scala abstract type representing type of subclass

开发者 https://www.devze.com 2023-03-24 06:25 出处:网络
I\'m looking for a way to define a method that returns a type T where T = the type of the subclass. I know I could possibly do this using abstract types, but dislike the overhead of having to redefin

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

I know I could possibly do this using abstract types, but dislike the overhead of having to redefine T for each subclass.

Some sample code:

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 exten开发者_如何转开发ds MyClass {
   type T = ChildClass
}

Possibly a new language feature has made this easier? Or can I use this.type in some way? It's important to me that I be able to define a helper class that can call into foo in this way.


If you are always returning this, then you can indeed have as return type this.type. Or have you tried it already?

this.type is especially useful e.g. when you want to chain calls to the same object, or provide a static guarantee that you will be returning the same object (and not a copy). For instance, Buffers in Scala have the append operation :+, which returns a Buffer[A], and +=, which returns this.type. The former duplicates the mutable sequence; the latter guarantees that you update the original object.


To follow up on Jean-Phillippe's answer, who wrote his exactly when I'm writing mine, here's 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>
  }
}


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消