Kotlin常用语法

java中的switch

int test=1;
switch(test){
    case 1:
      break;
   default:
      break;
}

kotlin使用when代替java中的switch,但比switch强大的多

when(test){
 var test:Int =0
        when(test){
            is Int,0 -> Log.e("tag","test is int and test=0")
            1-> "test=1"
            
            else -> Log.e("tag","test is nothing")
        }
}
//可以作为表达式并返回结果
val x:String=""
val isString = when(x){
      is String -> x is String
      else -> false
 }

for循环

java:
for(int i=0;i<10;i++){
}

kotlin:
 for (i in 0..4){
}
var list = listOf("1","2","3")
 //循环遍历
 for (i in list){
//可以直接使用list中的item对象
    i.length
}
list.forEach { 
    it.length
}

你可能感兴趣的:(Kotlin常用语法)