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.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 a compile-type type name, while classOf
is an operator that gets called at runtime to obtain a java.lang.Class
object. You can't use classOf[this]
ever, because the parameter needs to be a type name. Your two options when trying to obtain a java.lang.Class
object are to call classOf[TypeName]
or this.getClass()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With