Something in java like

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

现在应该把它转换成Kotlin ,就像

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

推荐答案

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

多亏了inlining,这将和从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.

Kotlin相关问答推荐

Jetpack Compose中的数字 Select 器问题

我如何测试一个可组合组件没有显示,但如果它不存在也接受?

在Kotlin中,我是否可以访问已知的WHEN子句值?

多模块Kotlin项目中的FreeFair

Kotlin扩展函数未调用Hibernate/JPA中的重写函数

为什么可组合对象看似无状态(唯一传递的参数是函数,而不是状态),但会进行重组

合并状态流

Kotlin Path.useLines { } - 如何不获取 IOException("Stream closed")?

如何在 Kotlin 中为变量分配另一个变量的值?

Kotlin:伴随对象内的函数扩展

Anko 中的水平线性布局

Kotlinwhen表达式在使用主题时是否支持复合布尔表达式?

将ExpectedException与Kotlin一起使用

如何在kotlin语言中将字符转换为ascii值

Kotlin:如何从另一个类访问字段?

未解决的参考 dagger 2 + kotlin + android gradle

在 sharedPref.getString 中有一个默认值有什么意义?

如何计算Kotlin中的百分比

在 intelliJ 元素中集成 Kotlinx 协程

如何判断数据是否插入到房间数据库中