在Kotlin中,如果函数没有返回值,函数会默认被当成 Unit 类型。而 Java 中是void 关键字来标识的。
它们的区别是什么? Unit 是一个类型,而void 是一个关键字。
val : 引用不可变, 使用 val声明的变量具有Java 中的final关键字效果。这里强调的是引用不可变。
优先使用val 来避免副作用:尽可能采用val、不可变对象及纯函数老设计程序。
Kotlin 天然支持了部分函数式特性。函数式语言一个典型的特征就在于 函数是头等公民。
高阶函数(更加抽象):接受一个或多个过程(函数)为参数;或者以一个过程(函数)作为返回结果。
fun View.invisible(){
this.visibility = View.INVISIBLE
}
面向表达式编程:表达式和语句是不同的概念。
Kotlin中的 “?:”:这里的问号和冒号必须放在一起使用,它被称为Elvis运算符,或者null 合并运算符。Kotlin中可以用"?"来表示一种类型的可空性,我们可以用"?:"来给一种可空类型的变量指定为空的情况下的值。
When表达式:
for 循环
for(i in 1..10 step 2) print("$i ")
>>>1 3 5 7 9
for(i in 10 downTo 1 step 2) print("$i ")
>>> 10 8 6 4 2
for(i in 1 until 10) print("$i ")
>>>1 2 3 4 5 6 7 8 9
"a" in listOf("b","c")
>>> res4: kotlin.Boolean = false
"a" !in listOf("b","c")
>>> res5: kotlin.Boolean = true
val array = listOf("a","b","c","d")
for (c in array) print("$c ")
println("------------------")
for((index,value) in array.withIndex()){
println("index $index --> value $value ;")
}
>>>> a b c d ------------------
>>> index 0 --> value a ;index 1 --> value b ;index 2 --> value c ;index 3 --> value d ;
中缀表达式:A 中缀方法 B。
val map = mapOf(
1 to "one",
2 to "two",
3 to "three"
)
for(m in map){
println("${m.key}--->${m.value}")
}
>>> 1--->one
>>> 2--->two
>>> 3--->three
class Person{
infix fun called(name: String){
println("My name is $name")
}
}
fun main() {
val p = Person()
p called "小明"
}
>>> My name is 小明
字符串定义和操作
val str = """ \n \n ///// \\\\ ... """
println(str)























