浏览器中输入网址:play.kotlinlang.org 进去后黏贴代码点击Run就可以看到结果了。
- when 语句允许传入任何类型的参数,然后在when结构体中定义一系列条件
- when还可以进行类型匹配
/** * You can edit, run, and share this code. * play.kotlinlang.org */ fun main() { println("Hello, world!!!") val tom_score=getScore("Tom") println(tom_score) val tom_score2=getScore("Tom") println(tom_score2) val lily_score2=getScore("Lily") println(lily_score2) //演示when的类型匹配机制 val intnum=0 val doublenum=10.665678 val longnum=10L checkNumber(intnum) checkNumber(doublenum) checkNumber(longnum) } fun getScore(name:String)=if(name=="Tom"){86} else if(name=="Jim"){77} else if(name=="Jack"){95} else if(name=="Lily"){100} else {0} //下面考虑用when语句来改写上面的函数: when 语句允许传入任何类型的参数,然后在when结构体中定义一系列条件 fun getScore2(name:String)=when(name){ "Tom"->86 "Jim"->77 "Jack"->95 "Lily"->100 else ->0 } //when还可以进行类型匹配 fun checkNumber(num:Number){ when(num){ is Int ->println("Number is Int") is Double->println("Number is Double") else->println("Number not support") } }
运行结果:
Hello, world!!! 86 86 100 Number is Int Number is Double Number not support