{Kotlin學(xué)習(xí)日記}Day18 Koan第二關(guān)

大家好,我是William。

今天進(jìn)入Koan第二關(guān),本關(guān)要從Java代碼轉(zhuǎn)換到Kotlin代碼,一起來闖關(guān)吧。

先附上闖關(guān)鏈接:
https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Java%20to%20Kotlin%20conversion/Task.kt

Introduction

Java to Kotlin conversion

We have a handy tool for Java developers: Java to Kotlin converter. It works better in IntelliJ IDEA, but you can try it online as well. To become familiar with it, please convert the code below. Copy Java code, choose 'Convert from Java' above and copy the result function back.

public class JavaCode {
    public String toJSON(Collection<Integer> collection) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        Iterator<Integer> iterator = collection.iterator();
        while (iterator.hasNext()) {
            Integer element = iterator.next();
            sb.append(element);
            if (iterator.hasNext()) {
                sb.append(", ");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}

譯:
本題要求你使用Java to Kotlin converter工具,把上面的Java代碼通過官方提供的工具轉(zhuǎn)成Kotlin代碼。

解:
切記不是要求你根據(jù)Java代碼來手打Kotlin代碼(其實(shí)這么做也沒問題,前提是你要非常熟悉Kotlin同時(shí)也不忘Java)。

答:
先復(fù)制Java代碼。
然后點(diǎn)擊這個(gè)按鈕。


Java to Kotlin converter

把Java代碼粘貼到彈窗的左邊文本框。
然后把生成得到的Kotlin代碼復(fù)制粘貼到答題處,記得點(diǎn)擊Run按鈕。
想要check通過就看看人家的Test.kt單元測試用例,轉(zhuǎn)換后代碼如下:

class JavaCode {
  fun toJSON(collection:Collection<Int>):String {
    val sb = StringBuilder()
    sb.append("[")
    val iterator = collection.iterator()
    while (iterator.hasNext()) {
      val element = iterator.next()
      sb.append(element)
      if (iterator.hasNext()) {
        sb.append(", ")
      }
    }
    sb.append("]")
    return sb.toString()
  }
}

小結(jié)

今天這一關(guān)名義上是叫你用converter工具,實(shí)際用意是讓你能夠平穩(wěn)地從Java思維過渡到Kotlin思維。所以記得多看Basic Syntax的內(nèi)容,基礎(chǔ)語法糖要牢記。

Basic Syntax 傳送門:
http://kotlinlang.org/docs/reference/basic-syntax.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容