一、Null 相關(guān)
Strict null safety
1、Safe call
override fun onCreate(savedInstanceState : Bundle?){
super.onCreate(savedInstanceState)
val locked : Boolean? = savedInstanceState?.getBoolean("locked")
}
當(dāng)
savedInstanceState為空時(shí),表達(dá)式直接返回null,反之執(zhí)行表達(dá)式
2、Elvis operator
override fun onCreate(savedInstanceState : Bundle?){
super.onCreate(savedInstanceState)
val locked : Boolean? = savedInstanceState?.getBoolean("locked") ?: false
}
?:操作符,例如:a ?: b如果a不為空,則直接返回,反之,返回b
3、Not null assertion
override fun onCreate(savedInstanceState : Bundle?){
super.onCreate(savedInstanceState)
val locked : Boolean = savedInstanceState!!.getBoolean("locked")
}
當(dāng)使用
!!時(shí),必須要確保當(dāng)前變量是不為空的,否則,會(huì)報(bào)NullPointException,最好不用該操作符
4、let
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedInstanceState?.let{
println(it.getBoolean("isLocked"))
}
}
若
savedInstanceState為空,直接返回null,反之,執(zhí)行let表達(dá)式
二、轉(zhuǎn)換相關(guān)
Normal cast
val fragment: Fragment = ProductFragment()
val productFragment: ProductFragment = fragment as ProductFragment
1、unsafe cast
val fragment : String = "ProductFragment"
val productFragment : ProductFragment = fragment as ProductFragment
\\ Exception: ClassCastException(編譯期)
2、safe cast
val fragment : String = "ProductFragment"
val productFragment : ProductFragment? = fragment as? ProductFragment
注意:safe cast 使用
ProductFragment?替代ProductFragment
3、Non-nullable smart cast
fun setView(view: View?){
if (view == null)
return
//view is casted to non-nullable
view.isShown()
}
==
fun verifyView(view: View?){
view ?: return
//view is casted to non-nullable
view.isShown()
//..
}
//if want to throw exception
fun setView(view: View?){
view ?: throw RuntimeException("View is empty")
//view is casted to non-nullable
view.isShown()
}
三、Control flow
1、The if statement
val hour = 10
val greeting = if (hour < 18) {
//some code
"Good day"
} else {
//some code
"Good evening"
}
println(greeting) // Prints: "Good day"
//或
val age = 18
val message = "You are ${ if (age < 18) "young" else "of age" } person"
println(message) // Prints: You are of age person
2、The when expression
// one
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> println("x is neither 1 nor 2")
}
// two
val vehicle = "Bike"
val message= when (vehicle) {
"Car" -> {
// Some code
"Four wheels"
}
"Bike" -> {
// Some code
"Two wheels"
}
else -> {
//some code
"Unknown number of wheels"
}
}
println(message) //Prints: Two wheels
// three(處理多個(gè)值,使用逗號(hào))
val vehicle = "Car"
when (vehicle) {
"Car", "Bike" -> print("Vehicle")
else -> print("Unidentified funny object")
}
// four(判斷參數(shù)的類型)
val name = when (person) {
is String -> person.toUpperCase()
is User -> person.name
//Code is smart casted to String, so we can
//call String class methods
// five(判斷參數(shù)是否被包含)
val riskAssessment = 47
val risk = when (riskAssessment) {
in 1..20 -> "negligible risk"
!in 21..40 -> "minor risk"
!in 41..60 -> "major risk"
else -> "undefined risk"
}
println(risk) // Prints: major risk
}
// six(復(fù)雜類型的 when,可以替代 if...else if)
val riskAssessment = 80
val handleStrategy = "Warn"
val risk = when (riskAssessment) {
in 1..20 -> print("negligible risk")
!in 21..40 -> print("minor risk")
!in 41..60 -> print("major risk")
else -> when (handleStrategy){
"Warn" -> "Risk assessment warning"
"Ignore" -> "Risk ignored"
else -> "Unknown risk!"
}
}
println(risk) // Prints: Risk assessment warning
// seven(條件 true/false 處理)
private fun getPasswordErrorId(password: String) = when {
password.isEmpty() -> R.string.error_field_required
passwordInvalid(password) -> R.string.error_invalid_password
else -> null
}
// eight(省略 else,因?yàn)榭赡艿姆种б驯涣信e)
val large:Boolean = true
when(large){
true -> println("Big")
false -> println("Big")
}
3、Break continue
// continue、break 作用于當(dāng)前 `循環(huán)`
val intRange = 1..5
for(value in intRange) {
if(value == 3)
continue
println("Outer loop: $value ")
for (char in charRange) {
println("\tInner loop: $char ")
}
}
// continue@outer、break@outer(作用于 `外層循環(huán)`)
val charRange = 'A'..'B'
val intRange = 1..6
outer@for(value in intRange) {
println("Outer loop: $value ")
for (char in charRange) {
if(char == 'B')
break@outer
println("\tInner loop: $char ")
}
}
// return 將會(huì)退出所有的循環(huán)
fun doSth() {
val charRange = 'A'..'B'
val intRange = 1..6
for(value in intRange) {
println("Outer loop: $value ")
for (char in charRange) {
println("\tInner loop: $char ")
return
}
}
}