如何将Java赋值表达式转换为Kotlin

如何将Java赋值表达式转换为Kotlin

本文介绍了如何将Java赋值表达式转换为Kotlin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java中的东西

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

现在它应该转换为kotlin,如

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)

但它不正确。

这是我得到的错误:

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) { }
}


推荐答案

正如@AndroidEx正确指出的那样,与Java不同,赋值不是Kotlin中的表达式。原因是通常不鼓励具有副作用的表达。请参阅关于类似的主题。

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) { ... }

另一个是使用stdlib中的函数,如,它以接收者作为参数执行lambda并返回lambda结果。 apply run 有类似的语义。

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 }) { ... }

感谢,这将与从lambda取得的普通代码一样高效。

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

InputStream 的示例看起来像

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

另外,考虑函数用于读取 ByteArray 来自 InputStream

这篇关于如何将Java赋值表达式转换为Kotlin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:15