Kotlin For Android 笔记(一)

作者: Kotyo | 来源:发表于2019-02-11 14:47 被阅读5次

一、Null 相关


Strict null safety

1、Safe call

override fun onCreate(savedInstanceState : Bundle?){
   super.onCreate(savedInstanceState)
   val locked : Boolean? = savedInstanceState?.getBoolean("locked")
}

savedInstanceState 为空时,表达式直接返回 null,反之执行表达式

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") 
}

当使用 !! 时,必须要确保当前变量是不为空的,否则,会报 NullPointException,最好不用该操作符

4、let

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    savedInstanceState?.let{
    println(it.getBoolean("isLocked")) 
  }
}

savedInstanceState 为空,直接返回 null,反之,执行 let 表达式

二、转换相关


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(处理多个值,使用逗号)
val vehicle = "Car"
when (vehicle) {
    "Car", "Bike" -> print("Vehicle")
    else -> print("Unidentified funny object")
}

// four(判断参数的类型)
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(判断参数是否被包含)
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(复杂类型的 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,因为可能的分支已被列举)
val large:Boolean = true
when(large){
    true -> println("Big")
    false -> println("Big")
}

3、Break continue

// continue、break 作用于当前 `循环`
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(作用于 `外层循环`)
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 将会退出所有的循环
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
    }
  }
}

相关文章

网友评论

    本文标题:Kotlin For Android 笔记(一)

    本文链接:https://www.haomeiwen.com/subject/qalijqtx.html