How to convert Java assignment expression to Kotlin

后端 未结 6 2123
小鲜肉
小鲜肉 2020-11-30 07:14

Something in java like

int a = 1, b = 2, c = 1;
if ((a = b) !=c){
    System.out.print(true);
}

now it should be converted to kotlin like<

6条回答
  •  再見小時候
    2020-11-30 08:11

    Java: (a = b) != c

    Kotlin: b.also { a = it } != c


    Around OP's question:

    Unlike the accepted answer, I recommend using Kotlin's also function, instead of let:

    while (input.read(bytes).also { tmp = it } != -1) { ...
    

    Because T.also returns T (it) itself and then you can compare it with -1. This is more similar to Java's assignment as an expression.


    See "Return this vs. other type" section on this useful blog for details.

提交回复
热议问题