这一节用个小例子来理解下密封类及let、run、apply、also、with之间的区别
Java有枚举,Kotlin也有枚举,但多了一个密封类,密封类就是子类有限的类
/**
* 密封类
*/
sealed class Language{
class Java : Language(){
fun println(){
println("${javaClass.name}")
}
}
class Kotlin : Language(){
fun println(){
println("${javaClass.name}")
}
}
class Python : Language(){
fun println(){
println("${javaClass.name}")
}
}
class Swift : Language(){
fun println(){
println("${javaClass.name}")
}
}
}
定义一个类
class Programmer(val name: String,val age: Int,val language: Language){
override fun toString(): String {
return "$name - $age - ${language.javaClass.simpleName} engineer"
}
fun work(){
println("$name codeing")
}
}
看看 let run apply also with 有什么区别
fun main(args: Array<String>) {
println("Hello World")
//fun <T, R> T.let(block: (T) -> R): R = block(this)
//可以使用it关键字返回实体,单入参返回最后一行
val programmer1 = Programmer("John",25,Language.Kotlin())
val ss = programmer1?.let {
println(it.toString())
it.work()
}
//fun <T, R> T.run(block: T.() -> R): R = block()
//可以使用this关键字返回实体,单入参返回最后一行
val programmer2 = Programmer("Aluxe",28,Language.Python())
programmer2?.run {
println(toString())
this.work()
}
//fun <T> T.apply(block: T.() -> Unit): T { block(); return this }
//可以使用this关键字返回实体,单入参无返回。方法体返回this
val programmer3 = Programmer("Alice",21,Language.Swift())
programmer3?.apply {
println(this.toString())
}.work()
//fun <T> T.also(block: (T) -> Unit): T { block(this); return this }
//可以使用it关键字返回实体,单入参无返回。方法体返回this
val programmer4 = Programmer("Chen",31,Language.Java())
programmer4?.also {
println(it.toString())
}.work()
//fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
//可以使用this关键字返回实体,接收2个入参,第2个入参返回最后一行。
val programmer5 = Programmer("Smith",19,Language.Python())
with(programmer5){
println(this.toString())
work()
}
}
网友评论