Kotlin优点总结

一:项目中不再使用findViewById
程序中布局文件写的多了,使用findViewById得到控件也成为一个很大的工作量,虽然使用插件可以一键获取,但是也要申明一堆变量,影响美观哦。使用Kotlin开发很快速的将此问题解决,并且可以直接赋值,只需要在项目gradle文件中引用扩展插件即可
classpath”org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version”
原始代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
btKey = (Button) findViewById(R.id.bt_key);
btKey1 = (Button) findViewById(R.id.bt_key1);
btKey2 = (Button) findViewById(R.id.bt_key2);
btKey3 = (Button) findViewById(R.id.bt_key3);
btKey4 = (Button) findViewById(R.id.bt_key4);
btKey5 = (Button) findViewById(R.id.bt_key5);
btKey6 = (Button) findViewById(R.id.bt_key6);
btKey7 = (Button) findViewById(R.id.bt_key7);
btKey8 = (Button) findViewById(R.id.bt_key8);
tv = (TextView) findViewById(R.id.bt_key_tv);
tv.setText(“原始赋值”);
}

引用后代码如下:
class Main2Activity : SOTPBaseActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)
    kotlin_tv.setText("自动获取ID")或 kotlin_tv.text="直接赋值"
}

}
注:kotlin_tv控件变量名与布局文件中的id必须一致
导入包名 import kotlinx.android.synthetic.main.布局名称(activity_main2.*)
二:事件无需再New,全程不用加分号
直接调用如下:
这里写图片描述

三:空检测,非运行时检测
var num: String = null 编译时直接报错
var num : String ?=null 允许num为空值
println(num .length)


输出结果:
null
避免空指针的发生,但前提是不要重新赋值
四:不需要getter/setter方法
java语言:
public class User {
private String name;
private String age;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAge() {
    return age;
}

public void setAge(String age) {
    this.age = age;
}

}
Kotlin语言:
class User {
var name: String? = null
var age: String? = null
}
调用时只需要创建对象,直接引用变量赋值,操作如下:
val user = User()
//赋值
user.name = “tutu”
user.age = “23”
//取值
val name = user.name
val age = user.age
节省了不少工作量哦~✌,本人是刚开始了解,如有错误,欢迎纠正!!

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值