gpt4 book ai didi

class - Kotlin 类中 "this"的用途

转载 作者:行者123 更新时间:2023-12-02 13:03:13 25 4
gpt4 key购买 nike

关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

2年前关闭。




Improve this question




我正在尝试解决 this 的目的在类里面。考虑以下示例:

class TestMe {

var a: Int = 1
var b: Int = 2

fun setValA(value: Int) {
this.a = value
}
fun setValB(value: Int) {
b = value
}
}

val testInstance1 = TestMe()
val testInstance2 = TestMe()

testInstance1.setValA(3)
testInstance1.setValB(4)

println("instance 2A: ${testInstance2.a}, instance 2B: ${testInstance2.b}") // 1 2
println("instance 1A: ${testInstance1.a}, instance 1B: ${testInstance1.b}") // 3 4

看来我可以直接省略 this值和结果将是相同的。有什么我在这里想念的吗?

非常感谢!

最佳答案

是的,和 Java 一样,但是如果 a 会出现问题也是参数名称:

fun setValA(a: Int) {
a = a
}

编译错误:
Val cannot be reassigned

然后你将不得不使用 this :
fun setValA(a: Int) {
this.a = a
}

关于class - Kotlin 类中 "this"的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59487471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com