标准函数with
with函数接收两个参数,第一个参数是任意类型的对象,第二个是Lambda表达式。with函数会在Lambda表达式中提供第一个参数的上下文,并使用Lambda表达式中的最后一行代码作为返回值返回。
fun test() {
val list = listOf("Apple", "Banana", "Orange")
val result = with(StringBuilder()) {
append("开始吃水果")
for (fruit in list) {
append(fruit).append("\n")
}
append("水果都被吃完了")
toString()
}
println(result)
}
标准函数run
run函数不能直接调用,一定要调用某个对象的run函数才行,run函数只接收一个Lambda表达式作为参数,并且会在Lambda表达式中提供上下文,并把Lambda表达式的最后一行代码作为返回值返回
val list = listOf("Apple", "Banana", "Orange")
val result = StringBuilder().run {
append("开始吃水果\n")
for (fruit in list) {
append(fruit).append("\n")
}
append("水果被吃完")
toString()
}
println(result)
标准函数apply
同样是在某个对象上调用,并接收一个Lambda表达式作为参数,但无法指定返回值
val intent = Intent(context,MainActivity::class.java).apply {
putExtra("param1","1")
putExtra("param2","2")
}
延迟初始化
private lateinit var adapter: RecyclerListAdapter
private fun init() {
adapter = RecyclerListAdapter()
}
判断是否已经完成了初始化
if (!::adapter.isInitiallized) {
adapter = RecyclerListAdapter()
}
密封类
它是一个可继承的类,Kotlin编译器会自动检查密封类有哪些子类,并强制要求将每一个子类所对应的条件全部处理。密封类及其子类只能定义在同一个文件的顶层位置,不能嵌套在其他类中。
sealed class Result
class Success(val msg: String) : Result()
class Failure(val error: Exception) : Result()
fun getResultMsg(result: Result) = when (result) {
is Success -> result.msg
is Failure -> "Error is ${result.error.message}"
}
sealed class MsgViewHolder(view: View): RecyclerView.ViewHolder(view)
class LeftViewHolder(view: View): MsgViewHolder(view)
class RightViewHolder(view: View): MsgViewHolder(view)
class MsgAdapter(val msgList: List<String>): RecyclerView.Adapter<MsgViewHolder>() {
override fun onBindViewHolder(holder: MsgViewHolder, position: Int) {
val msg = msgList[position]
when (holder) {
is LeftViewHolder -> holder.leftMsg = msg.leftText
is RightViewHolder -> holder.rightMsg = msg.rightText
}
}
}
扩展函数
fun Any.log() {
Log.d("测试日志", this.toString())
}
fun test1() {
"Kotlin扩展函数真牛".log()
}
运算符重载
class Money(val value: Int) {
operator fun plus(money: Money): Money {
val sum = value + money.value
return Money(sum)
}
}
fun test2() {
val money1 = Money(5)
val money2 = Money(10)
val money3 = money1 + money2
println(money3.value)
}
多重重载
class Money(val value: Int) {
operator fun plus(money: Money): Money {
val sum = value + money.value
return Money(sum)
}
operator fun plus(newValue: Int): Money {
val sum = value + newValue
return Money(sum)
}
}
fun test2() {
val money1 = Money(5)
val money2 = Money(10)
val money3 = money1 + money2
val money4 = money3 + 20
println(money4.value)
println(money3.value)
}