fun main() {
var age = 12.3
if (age in 0.0..3.3){
println("婴幼儿")
}else if (age in 4.0..12.2){
println("少儿")
}else{
println("未知")
}
/**
* in 后面还可以接 list set 都可以
*/
if (age !in 0.0..3.3){
println("婴幼儿")
}
}
val school = "小s学"
val level = when (school) {
"学前班" -> "幼儿"
"小学" -> "少年"
"中学" -> "青年"
"高中" -> "学生"
else -> {
println("未知")
}
}
println(level)
fun main() {
println(doSomething(1, true))
}
private fun doSomething(age:Int,flag:Boolean):String{
return "result $age $flag"
}
fun main() {
println(doSomething(1, true))
TODO("nothing")
println("after nothing")
}
private fun doSomething(age:Int,flag:Boolean):String{
return "result $age $flag"
}
public class MyJava {
public static void is (){
System.out.println("is invoked");
}
public void saa (){
System.out.println("is invoked");
}
}
Kotlin 调用Java
fun main() {
MyJava.`is`()
MyJava().saa()
}
fun `**~special function with weird name~**`(){
}
fun main() {
val total = "Mississippi".count()
val total1 = "Mississippi".count { letter -> letter == 's' }
println(total)
println(total1)
}
fun main() {
// val blessingFunction:()->String={
// "我很牛逼"
// }
//
// println(blessingFunction())
val blessingFunction ={ name:String,year:Int ->
val holiday = "New Year ."
"$name, Happy $holiday $year"
}
println(blessingFunction("jack",3))
}
fun main() {
val getDiscountWords ={goodsName:String,hours:Int ->
val currentYear =2027
"${currentYear}年,双十一${goodsName}促销倒计时:$hours 小时"
}
showOnBoard("卫生纸",getDiscountWords)
}
//具名函数
fun showOnBoard(goodsName:String,getDiscountWords:(String,Int) ->String){
val hours:Int = (1..24).shuffled().last()
println(getDiscountWords(goodsName,hours))
}
fun main() {
showOnBoard1("卫生纸"){goodsName:String,hours:Int ->
val currentYear =2027
"${currentYear}年,双十一${goodsName}促销倒计时:$hours 小时"
}
}
//具名函数
fun showOnBoard1(goodsName:String,getDiscountWords:(String,Int) ->String){
val hours:Int = (1..24).shuffled().last()
println(getDiscountWords(goodsName,hours))
}
fun main() {
showOnBoard1("卫生纸"){goodsName:String,hours:Int ->
val currentYear =2027
"${currentYear}年,双十一${goodsName}促销倒计时:$hours 小时"
}
}
//具名函数
inline fun showOnBoard1(goodsName:String,getDiscountWords:(String,Int) ->String){
val hours:Int = (1..24).shuffled().last()
println(getDiscountWords(goodsName,hours))
}
fun main() {
showOnBoard2("牙膏",::getDiscountWords)
}
fun getDiscountWords(goodsName: String,hours:Int):String{
val currentYear =2027
return "${currentYear}年,双十一${goodsName}促销倒计时:$hours 小时"
}
//具名函数
fun showOnBoard2(goodsName:String,getDiscountWords:(String,Int) ->String){
val hours:Int = (1..24).shuffled().last()
println(getDiscountWords(goodsName,hours))
}
fun main() {
val configDiscountWords = configDiscountWords()
println(configDiscountWords("Jack"))
}
fun configDiscountWords():(String)->String{
return {goodsName:String ->
val currentYear =2027
val hours:Int = (1..24).shuffled().last()
"${currentYear}年,双十一${goodsName}促销倒计时:$hours 小时"
}
}
都是一种思想,lamdba表达式可以被当作函数参数和返回值传递嘛 在kotlin里