Foggy day
Kotlin - Elvis, null check 본문
Elvis of Kotlin is equal Optional.getOrElse() of java.
you can set the default value of variable by using { ?: }
class KotlinPlayGroundActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin_play_ground)
var str: String? = null
var strValueFirst = str ?: "It is null"
println("strValueFirst : $strValueFirst")
str = "It is not null"
var strValueSecond = str ?: "It is null"
println("strValueSecond : $strValueSecond")
var num: Int? = null
var intValueFirst = num ?: 0
println("intValueFirst : $intValueFirst")
num = 11
var intValueSecond = num ?: 0
println("intValueSecond : $intValueSecond")
}
}
'Kotlin' 카테고리의 다른 글
Kotlin - trimMargin, multiple line string (0) | 2021.03.19 |
---|---|
Kotlin - Kotlin casting, smart cast (0) | 2021.03.19 |
Kotlin - anonymous function (0) | 2021.03.17 |
Kotlin - extension function, fold, reduce (0) | 2021.03.17 |
Kotlin - function, expression syntax (0) | 2021.03.16 |