专栏首页Android NoteKotlin For Android 笔记(一)

Kotlin For Android 笔记(一)

一、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
    }
  }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Kotlin For Android 笔记(三)

    使用 @JvmOverloads 可以极大的简化构造函数的模板代码 Java 版本

    code_horse
  • 介绍Kotlin第一部分(翻译篇)

    code_horse
  • Java 8之lambda表达式(二)

    code_horse
  • Scala基础——容器操作

    羊羽shine
  • 【技术分享】特征值分解

      这里lambda表示特征向量v所对应的特征值。并且一个矩阵的一组特征向量是一组正交向量。特征值分解是将一个矩阵分解为下面的形式:

    腾讯智能钛AI开发者
  • scala基础学习--scala教程

    翻译自《big data analytics with spark》第二章Programming in Scala

    挖掘大数据
  • 重拾Kotlin(21)-委托

    委托模式是一种基本的设计模式,该模式下有两个对象参与处理同一个请求,接受请求的对象将请求委托给另一个对象来处理。Kotlin 原生支持委托模式,可以零样板代码来...

    叶应是叶
  • [PHP] 算法-根据前序和中序遍历结果重建二叉树的PHP实现

    陶士涵
  • 聊聊kafka client chunkQueue 与 MaxLag值

    前面一篇文章讨论了ConsumerFetcherManager的MaxLag与ConsumerOffsetChecker的lag值的区别。但是关于MaxLag的...

    codecraft
  • 编程小知识之switch语句

    switch 语句大家都不陌生,平时在遇到较多相同的 if 语句判断时就会想到他,举个简单的例子:

    用户2615200

扫码关注云+社区

领取腾讯云代金券

玩转腾讯云 有奖征文活动