2016-04-27 74 views
17

喜歡的東西如何將Java賦值表達式轉換爲科特林在Java

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 

其實上面的代碼只是爲了澄清該問題的例子。這是我原來的代碼:

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

什麼錯誤(或錯誤),你好嗎? –

+0

in「(a = b)」錯誤:(99,9)Kotlin:賦值不是表達式,只有表達式在此上下文中才允許使用 –

回答

14

正如@AndroidEx正確指出的,與Java不同,賦值不是Kotlin中的表達式。原因是通常不鼓勵帶有副作用的表情。有關類似主題,請參閱this discussion

一個解決方案是隻分裂表達和移動分配出條件塊:

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

另一個是使用的功能從STDLIB像let,其與所述接收器作爲參數並返回執行拉姆達拉姆達結果。 applyrun具有相似的語義。

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

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

由於inlining,這將是從拉姆達採取明碼那樣高效。


您與InputStream例子看起來像

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

此外,考慮readBytes功能用於從InputStream閱讀ByteArray

8

分配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) 
    } 
} 
+0

即時嘗試使用I/O流,所以我必須將* a = b * in ** if()**或者** while()**,我應該怎麼做 –

+0

對不起,這裏是我原來的代碼'fun readFile(path:String):單元{} {var input:InputStream = FileInputStream(path ) VAR串:字符串= 「」 VAR TMP:INT = -1 變種字節:!=的ByteArray ByteArray的(1024) 而((TMP = input.read(字節))= - 1){ } }' –

+0

@ K.KSong編輯我的回答 – AndroidEx

4

這裏幾乎所有人都指出,任務並不是Kotlin中的表達式。但是,我們可以強制使用文字的功能分配到一個表達:

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

我認爲這可以幫助你:

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