Is there a way to make 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 of my subclasses? I’m 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 not possible ?
You need to use
this.typeinstead ofclassOf[this].Now to demonstrate that it works (in Scala 2.8)
this.typeis a compile-type type name, whileclassOfis an operator that gets called at runtime to obtain ajava.lang.Classobject. You can’t useclassOf[this]ever, because the parameter needs to be a type name. Your two options when trying to obtain ajava.lang.Classobject are to callclassOf[TypeName]orthis.getClass().