Scala中此的类型 [英] Type of this in Scala
问题描述
是否有一种方法可以使方法始终返回调用它的同一类的类型?
Is there a way to make a method to always return the type of the same class that called it ?
让我解释一下:
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
}
}
这有效,但是有没有一种方法可以不必在所有子类中覆盖named
函数呢?我正在寻找类似的东西(不起作用):
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 ?
推荐答案
您需要使用this.type
而不是classOf[this]
.
class Shape {
var mName: String = null
def named(name: String): this.type = {
mName = name
this
}
}
class Rectangle extends Shape {
}
现在要演示它的工作原理(在Scala 2.8中)
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
是编译类型的名称,而classOf
是在运行时被调用以获取java.lang.Class
对象的运算符.您永远无法使用classOf[this]
,因为该参数必须是类型名称.尝试获取java.lang.Class
对象时,您的两个选择是调用classOf[TypeName]
或this.getClass()
.
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()
.
这篇关于Scala中此的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!