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

์ฝ”ํ‹€๋ฆฐ์€ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•  ๋•Œ var ๋˜๋Š” val์ด ์‚ฌ์šฉ๋œ๋‹ค.

var : ๋ณ€๊ฒฝ ๊ฐ€๋Šฅํ•œ ์ปฌ๋ ‰์…˜

val : ๋ณ€๊ฒฝ ๋ถˆ๊ฐ€๋Šฅํ•œ ์ปฌ๋ ‰์…˜ (readOnly) => ์ปฌ๋ ‰์…˜์„ ์žฌํ• ๋‹นํ•˜๋ ค๊ณ  ํ•  ๊ฒฝ์šฐ ์˜ค๋ฅ˜ ๋ฐœ์ƒ

 

์•„๋ž˜์™€ ๊ฐ™์€ ์˜ˆ์‹œ๋ฅผ ์‚ดํŽด๋ณด์ž.

(์ฐธ๊ณ ๋กœ println( O ::class ) ๋Š” O์˜ ์ž๋ฃŒํ˜•์„ ์ถœ๋ ฅํ•œ๋‹ค.)

a

- var๋กœ ์„ ์–ธํ•œ a๋Š” ๊ฐ’์„ ๋ณ€๊ฒฝํ•ด๋„ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜์ง€ ์•Š๋Š”๋‹ค.

b

- val๋กœ ์„ ์–ธํ•œ b๋Š” ๊ฐ’์„ ๋ณ€๊ฒฝํ•˜๋ฉด ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

c, d

- val๋กœ ์„ ์–ธํ•œ ๋ณ€์ˆ˜์— : Int ์ฒ˜๋Ÿผ ์ž๋ฃŒํ˜•์„ ์„ ์–ธํ•ด์ฃผ๊ณ  ์ดํ›„์— ๊ฐ’์„ ๋„ฃ์–ด์ค„ ์ˆ˜๋„ ์žˆ๋‹ค.

- ์ด๋ ‡๊ฒŒ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•  ๋•Œ๋Š” ์ž๋ฃŒํ˜•์„ ๋ช…์‹œํ•ด์ฃผ๋Š” ๊ฒƒ์ด ์ข‹๋‹ค! ๋ช…์‹œํ•ด์ฃผ๋ฉด ๋‹ค๋ฅธ ์‚ฌ๋žŒ์ด ๋ดค์„ ๋•Œ๋„ ์•Œ์•„๋ณด๊ธฐ ์‰ฝ๋‹ค.

 

fun main() {
    var a = 1
    a = 2
    println(a)
    println(a::class)
    
    val b = 1
    //b = 2
    println(b)
    println(b::class)
    
    val c: Int
    c = 1
    println(c)
    println(c::class)
    
    val d: String
    d = "test"
    println(d)
    println(d::class)
    
}

 

 

 

์ฐธ๊ณ 

์ฝ”ํ‹€๋ฆฐ์„ ์„ค์น˜์—†์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์‚ฌ์ดํŠธ์ธ Kotlin Playground๋ฅผ ํ™œ์šฉํ–ˆ๋‹ค.

https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS45LjAiLCJwbGF0Zm9ybSI6ImphdmEiLCJhcmdzIjoiIiwibm9uZU1hcmtlcnMiOnRydWUsInRoZW1lIjoiaWRlYSIsImNvZGUiOiIvKipcbiAqIFlvdSBjYW4gZWRpdCwgcnVuLCBhbmQgc2hhcmUgdGhpcyBjb2RlLlxuICogcGxheS5rb3RsaW5sYW5nLm9yZ1xuICovXG5mdW4gbWFpbigpIHtcbiAgICB2YXIgYSA9IDFcbiAgICBhID0gMlxuICAgIHByaW50bG4oYSlcbiAgICBcbiAgICB2YWwgYiA9IDFcbiAgICAvL2IgPSAyXG4gICAgcHJpbnRsbihiKVxuICAgIFxuICAgIHZhbCBjOiBJbnRcbiAgICBjID0gMVxuICAgIHByaW50bG4oYylcbiAgICBcbn0ifQ==

 

Kotlin Playground: Edit, Run, Share Kotlin Code Online

 

play.kotlinlang.org

์ฝ”ํ‹€๋ฆฐ ๋ฌธ๋ฒ•์„ ์•Œ์•„๋ณด๊ธฐ ์œ„ํ•ด Kotlin Docs๋ฅผ ํ™œ์šฉํ–ˆ๋‹ค.

https://kotlinlang.org/docs/home.html

 

Kotlin Docs | Kotlin

 

kotlinlang.org

 

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

[Kotlin] class / data class / enum class  (0) 2023.08.20
[Kotlin] if / when  (0) 2023.08.20
[Kotlin] ? / ?. / ?: / !!.  (0) 2023.08.20