我有类似的代码
data class X{
fun getSomething(){
var y: Y()
//How can I write this
//this=y.doSomething()
}
}
class Y{
fun doSomething(): X{
//...
return x }
}
我想将this
分配给我从某个其他类中的其他方法返回的对象。
答案 0 :(得分:2)
您不能为this
分配任何内容,而且data
类应该是不可变的。只需重新分配您的参考即可:
data class X(val x: String) {
fun getSomething() = Y().doSomething()
}
class Y {
fun doSomething(): X {
return X("fromY")
}
}
fun main(args: Array<String>) {
val second = X("first").getSomething()
}