Android经验和架构

Kotlin Basic Syntax

2017-05-23  本文已影响6人  lhyz
fun sum(a: Int,b: Int) = a+b
print("$a+$b=" + sum(a, b))

使用$加关键字的方式在字符串中引用变量的值
使用${表达式}的方式在字符串中应用表达式的返回值

fun ex(obj: Any): Int {
    if (obj is String) {
        //类型被自动转换为String
        return obj.length
    }
    //此处obj类型仍然是Any
    return -1
}

每次使用 is 后都会对后面同一作用域内的参数进行类型转换

fun describe(obj: Any): String =
when (obj) {
    1          -> "One"
    "Hello"    -> "Greeting"
    is Long    -> "Long"
    !is String -> "Not a string"
    else       -> "Unknown"
}

when表达式

val x=3
if(x !in 1..10){
    print(x)
}

Ranges表达式

for(item in items){
    print(item)
}
collections
  .filter{ it.startsWith("a")}
  .sortedBy{it}
  .map{it.toUpperCase()}
  .forEach{println(it)}
上一篇 下一篇

猜你喜欢

热点阅读