๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ

[Kotlin] ? / ?. / ?: / !!.

category Web/Kotlin 2023. 8. 20. 00:31

? โžก null ํ—ˆ์šฉ

?. โžก null์ด๋ฉด null์„ ๋ฆฌํ„ดํ•˜๊ณ , null์ด ์•„๋‹ˆ๋ฉด ๋’ค์˜ ๋ช…๋ น์–ด๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค.

!!. โžก null์ด ์•„๋‹ˆ๋ผ๋Š” ๊ฐ€์ • ํ•˜์— ๋’ค์˜ ๋ช…๋ น์–ด๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค.

?: โžก null์ด๋ฉด ๋’ค์˜ ๋ช…๋ น์–ด๋ฅผ ์ˆ˜ํ–‰ํ•˜๊ณ , null์ด ์•„๋‹ˆ๋ฉด ์ˆ˜ํ–‰ํ•˜์ง€ ์•Š๋Š”๋‹ค.

 

์—„์ฒญ ํ—ท๊ฐˆ๋ฆฐ๋‹ค.

์ด๊ฑด ์•ผ๋งค ์•”๊ธฐ ๋ฐฉ๋ฒ•์ธ๋ฐ

 . ์ด ๋ถ™์œผ๋ฉด "null ์ด ์•„๋‹ ๋•Œ" (๋ถ€์ •)

 : ์ด ๋ถ™์œผ๋ฉด "null์ผ ๋•Œ" ๋ผ๊ณ  ์•”๊ธฐํ–ˆ๋‹ค. (๊ธ์ •)

 

fun main() {
    val str: String = "ABC"
    //val str: String = null //error
    val str2: String? = null	//? : null์„ ํ—ˆ์šฉํ•œ๋‹ค
    val str3: String? = "ABC"
    val str4: Int? = null	//? : null์„ ํ—ˆ์šฉํ•œ๋‹ค
    
    println(str.length)
    //println(str2.length) //error : need ?. or !!.
    
    // ?. : null safe call operator -> ?. ์•ž์˜ ๋ณ€์ˆ˜๊ฐ€ null์ด ์•„๋‹ˆ๋ฉด ๋’ค์˜ ๋ช…๋ น์–ด๋ฅผ ์‹คํ–‰ํ•œ๋‹ค. null์ด๋ฉด null์„ ๋ฆฌํ„ด
    println(str2?.length)
    println(str3?.length)
    
    // !!. : null์ด ์•„๋‹ˆ๋ผ๋Š” ๊ฐ€์ • ํ•˜์— ์‹คํ–‰. ์‹ค์ œ๋กœ๋Š” ์„ ์–ธํ•  ๋•Œ ?๋ฅผ ๋ถ™์—ฌ์„œ null์ด ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ์ง€๋งŒ, null์ด ์•„๋‹ˆ๋ผ๋Š” ๊ฒƒ์„ ๋ณด์žฅํ•ด์ค€๋‹ค.
    println(str3!!.length)
    //println(str2!!.length) //NullPointerException
    
    val str5: String? = "ABC"
    str5 ?: println("str5 is null!") //๋ฏธ์ถœ๋ ฅ
    
    val str6: String? = null
    str6 ?: println("str6 is null!")
}

์‹คํ–‰ ๊ฒฐ๊ณผ

 

'Web > Kotlin' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Kotlin] class / data class / enum class  (0) 2023.08.20
[Kotlin] if / when  (0) 2023.08.20
[Kotlin] ๋ณ€์ˆ˜ ์„ ์–ธ ์‹œ var / val ์ฐจ์ด  (0) 2023.08.18