前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Kotlin For Android 笔记(一)

Kotlin For Android 笔记(一)

作者头像
code_horse
发布2019-03-04 10:44:07
5340
发布2019-03-04 10:44:07
举报
文章被收录于专栏:Android Note

一、Null 相关


Strict null safety

1、Safe call

代码语言:javascript
复制
override fun onCreate(savedInstanceState : Bundle?){
   super.onCreate(savedInstanceState)
   val locked : Boolean? = savedInstanceState?.getBoolean("locked")
}

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

2、Elvis operator

代码语言:javascript
复制
override fun onCreate(savedInstanceState : Bundle?){
   super.onCreate(savedInstanceState)
   val locked : Boolean? = savedInstanceState?.getBoolean("locked") ?: false
}

?: 操作符,例如:a ?: b 如果a不为空,则直接返回,反之,返回b

3、Not null assertion

代码语言:javascript
复制
override fun onCreate(savedInstanceState : Bundle?){
   super.onCreate(savedInstanceState)
   val locked : Boolean = savedInstanceState!!.getBoolean("locked") 
}

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

4、let

代码语言:javascript
复制
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    savedInstanceState?.let{
    println(it.getBoolean("isLocked")) 
  }
}

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

二、转换相关


Normal cast

代码语言:javascript
复制
val fragment: Fragment = ProductFragment()
val productFragment: ProductFragment = fragment as ProductFragment

1、unsafe cast

代码语言:javascript
复制
val fragment : String = "ProductFragment"
val productFragment : ProductFragment = fragment as ProductFragment
\\ Exception: ClassCastException(编译期)

2、safe cast

代码语言:javascript
复制
val fragment : String = "ProductFragment"
val productFragment : ProductFragment? = fragment as? ProductFragment

注意:safe cast 使用 ProductFragment? 替代 ProductFragment

3、Non-nullable smart cast
代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
// 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

代码语言:javascript
复制
// 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
    }
  }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.02.11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、Null 相关
  • Strict null safety
    • 1、Safe call
      • 2、Elvis operator
        • 3、Not null assertion
          • 4、let
          • 二、转换相关
            • Normal cast
              • 1、unsafe cast
                • 2、safe cast
                • 三、Control flow
                  • 1、The if statement
                    • 2、The when expression
                      • 3、Break continue
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档