Android

[Kotlin] ๊ธฐ๋ณธ๋ฌธ๋ฒ•-1

MK_____ 2021. 11. 24. 09:50

// letํ•จ์ˆ˜์˜ ์‚ฌ์šฉ๋ฒ• -> if (null X) ์•ˆ์˜ ๋žŒ๋‹ค์‹ ์‹คํ–‰ํ•ด๋ผ!
        
    val email : String?= "mia@naver.com"
    email?.let {
        println("My email is ${email}")
    }

NunNull -> something ์œผ๋กœ ์ดˆ๊ธฐํ™”

 

null ์ด๋ผ ์•ˆ์— letํ•จ์ˆ˜ ๋žŒ๋‹ค์‹์ด ์•„์˜ˆ ์‹คํ–‰์ด ์•ˆ๋˜์„œ ์•„๋ฌด ๋ฐ˜์‘์ด ์—†๋Š”๊ฒƒ! (ํ•ด๊ฒฐ^ใ…‡^)

 

fun let(){

    // ? ์‚ฌ์šฉ๋ฒ•
    var name : String? = "mia" // null์ด๋ฉด mia๋กœ ์ดˆ๊ธฐํ™”
    name?.let{
        println(it)
    }

    // for๋ฌธ ์‚ฌ์šฉ๋ฒ•
   val students = arrayListOf("mia", "jino", "ted", "hoxvi")
    for (name in students) {
        println("${name}")
    }

    // ?: ์—˜๋น„์Šคํ”„๋ ˆ์Šฌ๋ฆฌ ใ…‹ null์ด๋ผ๋ฉด default ๊ฐ’ ์ •์˜

    val lastName : String? = null
    val fullName = name + " " + (lastName?:"No lastName")

    println(fullName)

}

    // !! ์‚ฌ์šฉ๋ฒ• -> null์ด ์•„๋‹˜์„ ํ™•์‹ ํ• ๋•Œ (์ง€์–‘ํ•˜๋Š” ํŽธ)
fun ignoreNull(str : String){
    val notNull : String = str!!
    val upper = notNull.toUpperCase()

    val notNull2 : String? = str!!
    val upper2 = notNull2.toUpperCase() // Error

 

// letํ•จ์ˆ˜์˜ ์‚ฌ์šฉ๋ฒ• -> if (null X) ์•ˆ์˜ ๋žŒ๋‹ค์‹ ์‹คํ–‰ํ•ด๋ผ!
        
    val email : String?= "mia@naver.com"
    email?.let {
        println("My email is ${email}")
    }

๋งŒ์•ฝ email์ด null์ด๋ฉด letํ•จ์ˆ˜๋Š” ์‹คํ–‰๋˜์ง€ ์•Š์Œ = ๋žŒ๋‹ค์‹ ์‹คํ–‰X