<android> kotlin体验 说说它的优缺点

 kotlin体验 说说它的优点
Kotlin 是一个基于 JVM 的新的编程语言,由  JetBrains 开发。
Kotlin可以编译成Java字节码,也可以编译成JavaScript,方便在没有JVM的设备上运行。
JetBrains,作为目前广受欢迎的Java IDE  IntelliJ 的提供商,在 Apache 许可下已经开源其Kotlin 编程语言。
Kotlin已正式成为Android官方支持开发语言。
都把他说的那么好,作为一直没有太怎么用过他的我来说(没用过原因有两个,一个是公司不让用,二个是感觉kotlin还是太年轻),但抵不住我的好奇,那今天就简单耍耍这个kotlin,他的语言风格对比java要简洁好多,比如说它断尾不需要分号,找控件id只需要导入个包就好,各种逻辑循环判断代码也简单简洁,着实为我们省下不少代码量,下面是我通过java代码翻译成的kotlin代码:

/**
 * 3 界面相关
 */
private fun demo_3() {
    val lv = findViewById(R.id.lv) as ListView
    val btn = findViewById(R.id.btn) as Button
    val checkBox2 = findViewById(R.id.checkBox2) as CheckBox
    checkBox2.isChecked = true
    checkBox2.setOnClickListener { Toast.makeText(this@KotLinDemo, "点击了!", Toast.LENGTH_SHORT).show() }

    btn.setOnClickListener { Toast.makeText(this@KotLinDemo, "点击了!", Toast.LENGTH_SHORT).show() }


    lv.adapter = object : BaseAdapter() {
        override fun getCount(): Int {
            return 10
        }

        override fun getItem(position: Int): Any? {
            return null
        }

        override fun getItemId(position: Int): Long {
            return 0
        }

        override fun getView(position: Int, convertView: View, parent: ViewGroup): View {
            val textView = TextView(this@KotLinDemo)
            textView.text = "具体实现请看代码kotlin/kotlin类" + position
            textView.setPadding(20, 20, 20, 20)
            return textView
        }
    }


}

/**
 * 2 基本语法
 */
private fun demo_2() {

    //if语句
    val a = 1
    val b = 2
    var c = a + b
    if (a > c) {
        c = a
    } else {
        c = b
    }

    //switch  case
    when (1) {
        1 -> {
        }

        2 -> {
        }
    }

    //while语句
    var d = 0
    while (d < 10) {
        if (d == c) {
            break
        } else {
            Log.e("" + d, "让我转吧!")
        }
        d++
    }

    //for语句
    val strings = ArrayList<String>()
    val stringStringHashMap = HashMap<String, String>()
    for (i in 0..9) {
        strings.add("我是" + i)
        stringStringHashMap.put("第" + i + "号", "刘大炮" + i)
    }

    //ArrayList 集合三种遍历

    //超级for循环遍历
    for (attribute in strings) {
        println("超级for循环遍历" + attribute)
    }

    //普通遍历
    for (i in strings.indices) {
        println("普通遍历:" + strings[i])
    }

    //用迭代器迭代
    val it = strings.iterator()
    while (it.hasNext()) {
        println("用迭代器迭代" + it.next())
    }

    //Hash 集合三种遍历

    //常用
    for (key in stringStringHashMap.keys) {
        println("常用:key:" + key + ",value:" + stringStringHashMap[key])
    }


    //遍历推荐使用
    for ((key, value) in stringStringHashMap) {
        println("遍历推荐使用:key:$key,value:$value")
    }

    //无法通过值来查询的遍历
    for (value in stringStringHashMap.values) {
        println("无法通过值来查询的遍历:value:" + value)
    }


    //三元表达
    val e = 12
    val f = 13
    Log.e("咳咳", "你是不是猪?" + if (e == f) true else false)


}


/**
 * 1 new 对象
 */
private fun demo_1() {
    val a = 1 //int
    val b = 1.0 //double
    val c = 1f //float
    val d = true // boolean
    val str = "Kotlin_Demo!" //String
    val strings1 = arrayOfNulls<String>(7) //固定数组
    val strs = arrayOf("a", "b", "c") //自由数组
    val stringBuffer = StringBuffer()
    val strings = ArrayList<String>()
    val stringStringHashMap = HashMap<String, String>()

    //接口实现
    val meUitls = MeUitls(object : MyListener {
        override fun shootMe(name: String, age: Int) {
            Toast.makeText(this@KotLinDemo, name + "打算杀了我,但是一看我才" + age + "岁,就放了我!", Toast.LENGTH_SHORT).show()
        }

        override fun eatMe(time: String, much: Int) {
            Toast.makeText(this@KotLinDemo, "小怪兽打算" + time + "吃了我,想啃我" + much + "下!", Toast.LENGTH_SHORT).show()
        }
    })
    meUitls.run()

    //匿名线程实现
    Thread(Runnable {
        //ui线程
        runOnUiThread { Toast.makeText(this@KotLinDemo, "我爱你Kotlin!", Toast.LENGTH_SHORT).show() }
    }).start()


}


/**
 * 接口实现onclick的点击事件

 * @param v
 */
override fun onClick(v: View) {

    when (v.id) {

        R.id.et_1 -> {
        }
    }

}


/**
 * 接口
 */
internal interface MyListener {
    fun shootMe(name: String, age: Int)

    fun eatMe(time: String, much: Int)
}

/**
 * 辅助类
 */
internal inner class MeUitls(var myListener: MyListener) {

    fun run() {
        myListener.eatMe("今晚12点", 100)
        myListener.shootMe("KotLin", 18)
    }
}
看到这里是不是很多地方感觉特别简单呢,平时的if else  三元表达,循环遍历等,在他面前仅仅几行代码就ok了。
下面是我们java代码,感兴趣的可以对比一下哦:
/**
 * 3 界面相关
 */
private void demo_3() {
    ListView lv = (ListView) findViewById(R.id.lv);
    Button btn = (Button) findViewById(R.id.btn);
    CheckBox checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
    checkBox2.setChecked(true);
    checkBox2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(KotLinJava.this, "点击了!", Toast.LENGTH_SHORT).show();
        }
    });

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(KotLinJava.this, "点击了!", Toast.LENGTH_SHORT).show();
        }
    });


    lv.setAdapter(new BaseAdapter() {
        @Override
        public int getCount() {
            return 10;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView textView = new TextView(KotLinJava.this);
            textView.setText("具体实现请看代码kotlin/kotlin类" + position);
            textView.setPadding(20, 20, 20, 20);
            return textView;
        }
    });


}

/**
 * 2 基本语法
 */
private void demo_2() {

    //if语句
    int a = 1;
    int b = 2;
    int c = a + b;
    if (a > c) {
        c = a;
    } else {
        c = b;
    }

    //switch  case
    switch (1) {
        case 1:
            break;

        case 2:
            break;
    }

    //while语句
    int d = 0;
    while (d < 10) {
        if (d == c) {
            break;
        } else {
            Log.e("" + d, "让我转吧!");
        }
        d++;
    }

    //for语句
    ArrayList<String> strings = new ArrayList<>();
    HashMap<String, String> stringStringHashMap = new HashMap<>();
    for (int i = 0; i < 10; i++) {
        strings.add("我是" + i);
        stringStringHashMap.put("第" + i + "号", "刘大炮" + i);
    }

    //ArrayList 集合三种遍历

    //超级for循环遍历
    for (String attribute : strings) {
        System.out.println("超级for循环遍历" + attribute);
    }

    //普通遍历
    for (int i = 0; i < strings.size(); i++) {
        System.out.println("普通遍历:" + strings.get(i));
    }

    //用迭代器迭代
    Iterator it = strings.iterator();
    while (it.hasNext()) {
        System.out.println("用迭代器迭代" + it.next());
    }

    //Hash 集合三种遍历

    //常用
    for (String key : stringStringHashMap.keySet()) {
        System.out.println("常用:key:" + key + ",value:" + stringStringHashMap.get(key));
    }


    //遍历推荐使用
    for (Map.Entry<String, String> entry : stringStringHashMap.entrySet()) {
        System.out.println("遍历推荐使用:key:" + entry.getKey() + ",value:" + entry.getValue());
    }

    //无法通过值来查询的遍历
    for (Object value : stringStringHashMap.values()) {
        System.out.println("无法通过值来查询的遍历:value:" + value);
    }


    //三元表达
    int e = 12;
    int f = 13;
    Log.e("咳咳", "你是不是猪?" + (e == f ? true : false));


}


/**
 * 1 new 对象
 */
private void demo_1() {
    int a = 1; //int
    double b = 1.0; //double
    float c = 1; //float
    boolean d = true; // boolean
    String str = "Kotlin_Demo!"; //String
    String[] strings1 = new String[7]; //固定数组
    String[] strs = {"a", "b", "c"}; //自由数组
    StringBuffer stringBuffer = new StringBuffer();
    ArrayList<String> strings = new ArrayList<>();
    HashMap<String, String> stringStringHashMap = new HashMap<>();

    MyObject myObject = new MyObject();
    myObject.setA(1);
    myObject.setB("2");
    myObject.setC(false);
    Log.e("", "对象里都有谁啊:" + myObject.getA() + myObject.getB() + myObject.isC());

    //接口实现
    MeUitls meUitls = new MeUitls(new MyListener() {
        @Override
        public void shootMe(String name, int age) {
            Toast.makeText(KotLinJava.this, name + "打算杀了我,但是一看我才" + age + "岁,就放了我!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void eatMe(String time, int much) {
            Toast.makeText(KotLinJava.this, "小怪兽打算" + time + "吃了我,想啃我" + much + "下!", Toast.LENGTH_SHORT).show();
        }
    });
    meUitls.run();

    //匿名线程实现
    new Thread(new Runnable() {
        @Override
        public void run() {

            //ui线程
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(KotLinJava.this, "我爱你Kotlin!", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }).start();


}


/**
 * 接口实现onclick的点击事件
 *
 * @param v
 */
@Override
public void onClick(View v) {

    switch (v.getId()) {

        case R.id.et_1:
            break;

    }

}


/**
 * 接口
 */
interface MyListener {
    void shootMe(String name, int age);

    void eatMe(String time, int much);
}

/**
 * 辅助类
 */
class MeUitls {
    MyListener myListener;

    public MeUitls(MyListener myListener) {
        this.myListener = myListener;
    }

    void run() {
        myListener.eatMe("今晚12点", 100);
        myListener.shootMe("KotLin", 18);
    }
}
直接java转kotlin代码运行会报错的,报 未初始化变量,这是由于Kotlin的语法规范所致,kotlin的变量一般需要在定义的时候就进行赋值。就需要使用kotlin的lateinit修饰符修饰定义的变量,以指定其将在稍后赋值。但目前Android Studio 2.3自带的Java代码转Kotlin代码的功能,并没有针对此种变量做处理,导致直接转换会报错。
虽然他那么强大,但是缺点当然也是有的,比如说代码提示过慢,用某些jar包时有时会有些冲突,编译速度慢等等。看到一篇好的博文,也是说关于kotlin的:
http://blog.csdn.net/ncuboy045wsq/article/details/74853107

猜你喜欢

转载自blog.csdn.net/csdn_lg_one/article/details/77783741