简体   繁体   English

将Java转换为Kotlin后出现“赋值不是表达式错误”

[英]“Assignments are not expressions error” after converting Java to Kotlin

I converted some Java classes to kotlin and an "Assignments are not expressions, and only expressions are allowed in this context" error pops up when I try to run this code which worked fine in Java: 我将一些Java类转换为kotlin并在尝试运行在Java中运行良好的代码时弹出了“赋值不是表达式,并且只允许在此上下文中使用表达式”错误:

@Throws(IOException::class)
private fun readAll(rd: Reader): String {
    val sb = StringBuilder()
    var cp: Int
    while ((cp = rd.read()) != -1) {
        sb.append(cp.toChar())
    }

    return sb.toString()
}

The line causing the problem: 导致问题的行:

while ((cp = rd.read()) != -1)

Exactly as the message says in Kotlin you can't use the assignment as an expression. 就像消息在Kotlin中所说的那样,您不能将赋值用作表达式。 You can do this: 你可以这样做:

private fun readAll(rd: Reader): String {
    val sb = StringBuilder()
    var cp: Int
    do {
        cp = rd.read()
        if (cp == -1)
            break
        sb.append(cp.toChar())      
    } while (true) // your choice here to stop the loop 
    return sb.toString()
}

In Kotlin you can't do this: 在Kotlin中,您无法执行以下操作:

while ((cp = rd.read()) != -1)

You should use something like this: 您应该使用这样的东西:

var cp = rd.read()
while (cp != -1) {
    // your logic here
    cp = rd.read()
}

Or something like this: 或类似这样的东西:

while (true) {
    val cp = rd.read()
    if (cp < 0) break

    // your logic here
}

Because assignment ( cp = rd.read() ) is expression in Java, but not in Kotlin. 因为赋值( cp = rd.read() )是Java中的表达式,但不是Kotlin中的表达式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Kotlin/Android 中的“赋值不是表达式”错误 - "Assignments are not expressions" error in Kotlin/Android 赋值不是表达式,在此上下文中只允许使用表达式 - 将Java转换为Kotlin时出错 - Assignments are not expressions, and only expressions are allowed in this context - Error when convert Java to Kotlin 在 Android 中将 Java 转换为 Kotlin 后出错 - Error after converting Java to Kotlin in Android 分配不是表达式,在这种情况下只能使用表达式-Kotlin - Assignments are not expressions and only expressions are allowed in this context - Kotlin 赋值不是表达式,在这种情况下只允许使用表达式 - Kotlin - Assignments are not expressions, and only expressions are allowed in this context - Kotlin 将 java 泛型转换为 kotlin 后出现类型不匹配错误 - Type mismatch error after converting java generic to kotlin 有没有办法解决这个 kotlin 中的“赋值不是表达式,并且在此上下文中只允许表达式” - is there a way for me to fix the " Assignments are not expressions, and only expressions are allowed in this context" in this kotlin if 语句:赋值不是表达式,在这个上下文中只允许表达式 kotlin - If statement: Assignments are not expressions, and only expressions are allowed in this context kotlin 将Java代码转换为Kotlin后出现IllegalStateException - IllegalStateException after converting java code to kotlin 从Java比较器转换后的Kotlin比较器 - Kotlin Comparator after converting from Java Comparator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM