Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

How to convert Java assignment expression to Kotlin

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

var a:Int? = 1
var b:Int? = 2
var c:Int? = 1
if ( (a = b) != c)
    print(true)

but it's not correct.

Here is the error I get:

in " (a=b)" Error:(99, 9) Kotlin: Assignments are not expressions, and only expressions are allowed in this context

Actually the code above is just an example to clarify the problem. Here is my original code:

fun readFile(path: String): Unit { 
    var input: InputStream = FileInputStream(path) 
    var string: String = "" 
    var tmp: Int = -1 
    var bytes: ByteArray = ByteArray(1024) 

    while((tmp=input.read(bytes))!=-1) { } 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @AndroidEx correctly stated, assignments are not expressions in Kotlin, unlike Java. The reason is that expressions with side effects are generally discouraged. See this discussion on a similar topic.

One solution is just to split the expression and move the assignment out of condition block:

a = b
if (a != c) { ... }

Another one is to use functions from stdlib like let, which executes the lambda with the receiver as parameter and returns the lambda result. apply and run have similar semantics.

if (b.let { a = it; it != c }) { ... }

if (run { a = b; b != c }) { ... }

Thanks to inlining, this will be as efficient as plain code taken from the lambda.


Your example with InputStream would look like

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

Also, consider readBytes function for reading a ByteArray from an InputStream.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...