变量的定义
private var tv:TextView?=null;//变量的定义
protected var num:Int=0;
接口调用中的!! 和?
class MainActivity : AppCompatActivity() {
private var tv:TextView?=null;//变量的定义
protected var num:Int=0;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main);
//tv=findViewById(R.id.tv);
//tv!!.setText("welocome");
tv?.setText("hello world");
}
}
!!.表示当前对象如果为空也执行,然后会抛出空异常
?.表示当前对象如果为空则不执行
findViewById
tv=findViewById(R.id.tv);
类继承,接口实现
class MainActivity : AppCompatActivity(), View.OnClickListener {
}
swith
java
switch (view.getId()){
case R.id.tv:
break;
case R.id.add:
break;
default:
break;
}
kotlin
when (view.id) {
R.id.tv -> {
}
R.id.add -> {
}
else -> {
}
}
类转换
java
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
kotlin
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
接口
有参数有返回值
java
private int sum(int a, int b) {
return a+b;
}
kotlin
private fun sum(a: Int, b: Int): Int {
return a + b
}
只有返回值
java
private int get() {
return 0;
}
kotlin
private fun get(): Int {
return 0
}
无参数,无返回值
java
private void dosomething() {
Log.d("tag","TOdo");
}
kotlin
private fun dosomething() {
Log.d("tag", "TOdo")
}
实例化对象
java
TextView tx = new TextView(context);
Button button = new Button(context);
kotlin
val tx = TextView(context)
val button = Button(context)
关于分号
kotlin 语法最后可以不用加 ‘;’ 分号