Scala教程
Scala面向对象
Scala高级

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()
    }
}
输出:
101 Martin

使用 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)
    }
} 
输出:
Rama 100
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4