Type of this in scala

Is there a way to force a method to always return the type of the same class that called it?

Let me explain:

class Shape { var mName: String = null def named(name: String): Shape = { mName = name this } } class Rectangle extends Shape { override def named(name: String): Rectangle = { super.named(name) this } } 

This works, but is there a way to do this without having to override the named function in all my subclasses? I am looking for something like this (which does not work):

 class Shape { var mName: String = null def named(name: String): classOf[this] = { // Does not work but would be great mName = name this } } class Rectangle extends Shape { } 

Any idea? Or is it impossible?

+7
source share
1 answer

You need to use this.type instead of classOf[this] .

 class Shape { var mName: String = null def named(name: String): this.type = { mName = name this } } class Rectangle extends Shape { } 

Now, to demonstrate that it works (in Scala 2.8)

 scala> new Rectangle().named("foo") res0: Rectangle = Rectangle@33f979cb scala> res0.mName res1: String = foo 

this.type is the type name of the compiled type, and classOf is the statement that is called at run time to get the java.lang.Class object. You cannot use classOf[this] ever, because the parameter must be a type name. Your two parameters, when trying to get the java.lang.Class object, should call classOf[TypeName] or this.getClass() .

+18
source

All Articles