Kotlin笔记1—基础
val 用于值从不更改的变量。使用 val 声明的变量无法重新赋值。
var 用于值可以更改的变量
一般不能为null val languageName: String = null // 错误
加了?可为null val languageName: String? = null // 正确
相当于三元运算符 ?:
val answerString: String = if (count == 42) {
"I have the answer."
} else if (count > 35) {
"The answer is close."
} else {
"The answer eludes me."
}
println(answerString)
条件表达式的另一种表示:用when
val answerString = when {
count == 42 -> "I have the answer."
count > 35 -> "The answer is close."
else -> "The answer eludes me."
}
println(answerString)
fun 函数名(参数:参数类型):返回值类型{
}
fun generateAnswerString(countThreshold: Int): String {
val answerString = if (count > countThreshold) {
"I have the answer."
} else {
"The answer eludes me."
}
return answerString
}
val answerString = generateAnswerString(42)
简化:省略局部变量
fun generateAnswerString(countThreshold: Int): String {
return if (count > countThreshold) {
"I have the answer."
} else {
"The answer eludes me."
}
}
进一步简化:省略return符号
fun generateAnswerString(countThreshold: Int): String = if (count > countThreshold) {
"I have the answer"
} else {
"The answer eludes me"
}
val stringLengthFunc: (String) -> Int = { input ->
input.length
}
// 调用
val stringLength: Int = stringLengthFunc("Android")
(String) -> Int 表示函数的类型
一个函数可以将另一个函数当作参数。将其他函数用作参数的函数称为“高阶函数”(相当于 Java 中使用回调接口相同)
fun stringMapper(str: String, mapper: (String) -> Int): Int {
// Invoke function
return mapper(str)
}
// 调用
stringMapper("Android", { input ->
input.length
})
// 简化调用(如果匿名函数是在某个函数上定义的最后一个参数,则您可以在用于调用该函数的圆括号之外传递它)
stringMapper("Android") { input ->
input.length
}
默认提供了构造函数和get/set方法
class Car {
val wheels = listOf<Wheel>()
}
// 调用
val car = Car() // construct a Car
val wheels = car.wheels // retrieve the wheels value from the Car
含有构造函数的类,构造函数里的参数带var 或者 val 时,该参数也是该类的属性
class Car(val wheels: List<Wheel>)
class A 等价于 class A { } 等价于 class A() 等价于 class A construct()