在Kotlin中的源码标准库(Standard.kt)中提供了一些Kotlin扩展的内置函数 更多
class ExampleUnitTest {
class User constructor(var name: String, var age: Int)
@Test
fun testLet() {
val user = User("张三", 2)
var userNull: User? = null
user.let {
println(it.name)
}
userNull?.let {
println(it.name)
}
userNull.let {
println(it?.name)
}
}
@Test
fun testAlso() {
val user = User("张三", 2)
var userNull: User? = null
user.also {
println(it.name)
}.also {
println(it.age)
}
}
@Test
fun testWith() {
val user = User("张三", 2)
var userNull: User? = null
with(user, {
println(name)
println("name:$name")
})
with(user) {
println(name)
println("name:$name")
name = "李四"
age = 5
}
with(userNull) {
println(this?.name)
println("name:${this?.name}")
}
}
@Test
fun testRun() {
val user = User("张三", 2)
var userNull: User? = null
val rsult = user.run {
println("name:$name")
true
}
println(rsult)
userNull.run {
println(this?.name)
}
}
@Test
fun testApply() {
val user = User("张三", 2)
var userNull: User? = null
user.apply {
println("name:$name")
}.apply {
println("name2:$name")
}
}
}
|