如何将 Java 赋值表达式转换为 Kotlin [英] How to convert Java assignment expression to Kotlin
问题描述
Java 中的一些东西
Something in java like
int a = 1, b = 2, c = 1;
if ((a = b) !=c){
System.out.print(true);
}
现在应该像 kotlin 一样转换成 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 正确指出的那样,赋值不是 Kotlin 中的表达式,与 Java 不同.原因是通常不鼓励具有副作用的表达式.请参阅此讨论类似的话题.
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 中的函数,例如 let
,它以接收者为参数执行 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 }) { ... }
另外,考虑 readBytes
函数用于从 InputStream
读取 ByteArray
.
Also, consider readBytes
function for reading a ByteArray
from an InputStream
.
这篇关于如何将 Java 赋值表达式转换为 Kotlin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!