Scala this
Scala this
在Scala 中,this 是一个关键字,用于引用当前对象。可以使用 this 关键字调用实例变量、方法、构造函数。
Scala this Example
在下面的例子中,
this是用于调用实例变量和主构造函数。
class thisExample{
var id:int = 0
var name: String = ""
def this(id:Int, name:String){
this()
this.id = id
this.name = name
}
def show(){
println(id+" "+name)
}
}
object MainObject{
def main(args:Array[String]){
var t = new thisExample(101,"Martin")
t.show()
}
}
输出:
使用 this 关键字调用 Scala 构造函数
在下面的示例中,this 用于调用构造函数。它说明了我们如何从其他构造函数调用构造函数。在调用其他构造函数时,您必须确保 this 必须是构造函数中的第一条语句,否则编译器会抛出错误。
class Student(name:String){
def this(name:String, age:Int){
this(name)
println(name+" "+age)
}
}
object MainObject{
def main(args:Array[String]){
var s = new Student("Rama",100)
}
}
输出: