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

时间:2016-04-27 02:31:10

标签: java kotlin

像java这样的东西

String x = imageTable;
                int firstPos = x.indexOf("start") + "start".length();
                int lastPos = x.indexOf("end", firstPos);
                String y = x.substring(0,firstPos) + ":" + x.substring(lastPos);
                y = y.replace("start:end", "");
                imageTable = y;

现在它应该转换为像kotlin一样

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

但这不正确。

这是我得到的错误:

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

6 个答案:

答案 0 :(得分:28)

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

一种解决方案就是分割表达式并将赋值移出条件块:

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

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

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

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

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

InputStream的示例看起来像

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

另外,请考虑使用readBytes函数从ByteArray读取InputStream

答案 1 :(得分:11)

Kotlin中的作业are not expressions,因此您需要在外面进行:

var a: Int? = 1
var b: Int? = 2
var c: Int? = 1

a = b
if (a != c)
    print(true)

对于使用InputStream的其他示例,您可以执行以下操作:

fun readFile(path: String) {
    val input: InputStream = FileInputStream(path)
    input.reader().forEachLine {
        print(it)
    }
}

答案 2 :(得分:8)

正如这里的每个人都指出的那样,作业不是Kotlin中的表达。但是,我们可以使用函数文字强制将赋值转换为表达式:

val reader = Files.newBufferedReader(path)
var line: String? = null
while ({ line = reader.readLine(); line }() != null) {
    println(line);
}

答案 3 :(得分:5)

Java (a = b) != c

科特琳b.also { a = it } != c


围绕OP的问题:

accepted answer不同,我建议使用Kotlin的 also 函数,而不要使用let

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

因为T.also本身返回Tit),然后您可以将其与-1进行比较。这与 Java的语句分配更相似。


有关详情,请参见this useful blog上的“返回此类型与其他类型” 部分。

答案 4 :(得分:0)

我认为这可能会对您有所帮助:

 input.buffered(1024).reader().forEachLine {
            fos.bufferedWriter().write(it)
        }

答案 5 :(得分:0)

kotlin的简单方法是

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