美文网首页
Kotlin VS Java【简要总结】

Kotlin VS Java【简要总结】

作者: LiveMoment | 来源:发表于2017-06-01 11:32 被阅读88次

Kotlin的优势:
1、代码简洁,行数少,减少出错
2、避免NullPointerException
3、findViewById
4、更容易的使用集合
5、不用写Util类

一、更简单的生成类:

data class Person(var name: String,
         var age: Int,
         var height: Float = 1.8f)

二、避免NullPointerException

val person: Person? = null
...
person?.name = "John"

? 运算符强制检查是否为空,如果是空则不继续进行

三、扩展函数,摆脱util类

fun Context.toast(text: String) = Toast.makeText(this, text, 
    Toast.LENGTH_SHORT).show()

声明了一个toast方法,这个方法的参数是一个String类型,这个方法可以在Activity或者其他Context实例中直接调用:

toast("Hi")

四、findViewById的最新简单写法:

button.setOnClickListener { my_text.text = "You've clicked a 
    button" }

其中第一个my_text是控件的id

原来的写法是:

 Button button = (Button) findViewById(R.id.button);
    final TextView text = (TextView) findViewById(R.id.my_text); 
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            text.setText("You've clicked a button");
        }
    });
}

五、使用集合更容易:

var students = listOf(
    Student("John", 0), 
    Student("Julia", 2), 
    Student("Matt", 1),
    Student("Katie", 0), 
    Student("Dan", 0)
)
var firstList = students.filter { it.mark == 0 }.take(3)
var secondList = students.filter { it.mark == 1 }.take(2)

第一个,过滤出分数为0的三个学生;第二个过滤出分数为1的两个学生

参考:
kotlin VS java:
http://blog.csdn.net/sergeycao/article/details/54984108

kotlin基本语法:
http://blog.csdn.net/u011976726/article/details/57121052

https://www.zhihu.com/question/32037895

react native
React Native for Android

相关文章

网友评论

      本文标题:Kotlin VS Java【简要总结】

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