如何在Kotlin中分配当前的类实例

时间:2018-08-29 13:56:23

标签: kotlin this

我有类似的代码

data class X{
    fun getSomething(){
    var y: Y()
    //How can I write this
    //this=y.doSomething()
    }
}

class Y{
    fun doSomething(): X{ 
    //...
    return x }
}

我想将this分配给我从某个其他类中的其他方法返回的对象。

1 个答案:

答案 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()
} 
相关问题