【scala关键字系列】 this 由来用法示例详解
文章目录
1. 由来
在Scala中,关键字this
用于表示当前对象的引用。它是面向对象编程语言中的一个常见概念,在Scala中用于指代当前类的实例。
当我们想要引入当前对象的类时,我们使用this关键字。
然后通过使用点操作符(.),我们可以使用this关键字引用实例变量、方法和构造函数。
this关键字也用于辅助构造函数。
2. 用法
this
:使用this
关键字可以在类的方法内部引用当前对象。this()
:在类的构造函数中,this()
表示调用当前类的其他构造函数,用于构造函数之间的互相调用。this.fieldName
:使用this.fieldName
可以访问当前对象的成员变量。this.methodName()
:使用this.methodName()
可以调用当前对象的方法。this.type
:this.type
是一个特殊的类型标注,表示当前对象的具体类型。
3. 示例
示例1:
object thisTest {
// Scala程序演示this关键字
class Addition(i: Int) {
// 使用this关键字
def this(i: Int, j: Int) {
this(i)
println(i + " + " + j + " = " + { i + j })
}
}
def main(args: Array[String]) {
var add = new Addition(15, 12)
}
}
//15 + 12 = 27
在上面的示例中,定义了一个Addition类,它包含一个参数,并且在该类中使用了带有两个参数i和j的this关键字的方法。在这个方法中,还调用了一个主构造函数(即this(i))。
示例2:
object thisTest1{
class Geeks {
var Lname: String = ""
var Articles = 0
// 使用this关键字
def this(Lname: String, Articles: Int) {
this()
this.Lname = Lname
this.Articles = Articles
}
def show() {
println("Language name " + Lname +
" published article " + Articles)
}
}
def main(args: Array[String]) {
var geeks = new Geeks("Scala", 105)
geeks.show()
}
}
//Language name Scala published article 105
正如我们所看到的,在上面的示例中,定义了一个使用this关键字的辅助构造函数,并使用this关键字调用了主构造函数。实例变量(即Lname、Articles)也使用点(.)操作符进行引用。
示例3
Self-types是一种声明一个trait必须被混入到另一个trait中的方式,即使它并没有直接继承它。这样可以使依赖的成员在不使用import的情况下可用。
Self-type是一种缩小this或其他标识符类型的方法,它别名为this。语法看起来像普通的函数语法,但意义完全不同。
要在trait中使用self-type,写一个标识符,另一个要混入的trait的类型,以及一个=>(例如someIdentifier: SomeOtherTrait =>)。
object thisTest2{
trait User {
def username: String
}
trait Tweeter {
this: User => // 重新分配this
def tweet(tweetText: String) = println(s"$username: $tweetText")
}
class VerifiedTweeter(val username_ : String) extends Tweeter with User { // 我们混入User因为Tweeter需要它
def username = s"real $username_"
}
def main(args: Array[String]): Unit = {
val realBeyoncé = new VerifiedTweeter("Beyoncé")
realBeyoncé.tweet("Just spilled my glass of lemonade") // 输出 "real Beyoncé: Just spilled my glass of lemonade"
}
}
//real Beyoncé: Just spilled my glass of lemonade
因为我们在trait Tweeter中使用了this: User =>,现在变量username在tweet方法的作用域内。这也意味着由于VerifiedTweeter扩展了Tweeter,它还必须混入User(使用with User)。
示例4(self)
object selfTest {
trait Logger {
self: Serializable =>
def log(message: String): Unit = {
println(s"[$self] $message")
}
}
class MyClass extends Logger with Serializable {
// ...
}
def main(args: Array[String]): Unit = {
val obj = new MyClass()
obj.log("Logging message")
}
}
//[selfTest$MyClass@4ec6a292] Logging message
4. 类似
在Scala中,除了this
关键字,还有一些类似的关键字和语法,如:
super
:用于引用父类的成员变量或方法。self
:可以用于指代当前对象自身,类似于this
,但用于更细粒度的类型定义。val
和var
:用于定义成员变量,也可以在类的方法中直接访问。
5. 区别
this
用于表示当前对象的引用,而super
用于表示父类的引用。this
可以在构造函数、方法和成员变量中使用,而self
主要用于更细粒度的类型定义。this.fieldName
用于访问当前对象的成员变量,而val
和var
用于定义成员变量并进行访问。