{Kotlin学习日记}Day18 Koan第二关

作者: William李梓峰 | 来源:发表于2017-07-25 13:43 被阅读84次

    大家好,我是William。

    今天进入Koan第二关,本关要从Java代码转换到Kotlin代码,一起来闯关吧。

    先附上闯关链接:
    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代码通过官方提供的工具转成Kotlin代码。

    解:
    切记不是要求你根据Java代码来手打Kotlin代码(其实这么做也没问题,前提是你要非常熟悉Kotlin同时也不忘Java)。

    答:
    先复制Java代码。
    然后点击这个按钮。


    Java to Kotlin converter

    把Java代码粘贴到弹窗的左边文本框。
    然后把生成得到的Kotlin代码复制粘贴到答题处,记得点击Run按钮。
    想要check通过就看看人家的Test.kt单元测试用例,转换后代码如下:

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

    小结

    今天这一关名义上是叫你用converter工具,实际用意是让你能够平稳地从Java思维过渡到Kotlin思维。所以记得多看Basic Syntax的内容,基础语法糖要牢记。

    Basic Syntax 传送门:
    http://kotlinlang.org/docs/reference/basic-syntax.html

    相关文章

      网友评论

        本文标题:{Kotlin学习日记}Day18 Koan第二关

        本文链接:https://www.haomeiwen.com/subject/keuwkxtx.html