본문으로 바로가기

1. Immutable & Mutable - Val vs Var

category Kotlin 2018. 5. 30. 12:52

1. Kotlin Val


val : read-only variable (like final), Not re-assign, 따라서 선언과 동시에 값을 가져야 한다.


2. Kotlin Var


var: mutable variable, 따라서 var의 value는 변경 가능


3. Kotlin Val & Var with Object's properties

1과 2와 동일


[Sample Code-1]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
data class Customer(val id: Int, var name: String)
 
fun main(args : Array<String>) {
    val cust = Customer(1"Jack")
    println("cust = $cust"// cust = Customer(id=1, name=Jack)
    // can not re-assign a new value
    cust.name = "Mary"
    println("cust = $cust"// cust = Customer(id=1, name=Mary)
    
    var cust2 = Customer(2"Peter")
    println("cust2 = $cust2"// cust2 = Customer(id=2, name=Peter)
    cust2.name = "Craig"
    println("cust2 = $cust2"// cust2 = Customer(id=2, name=Craig)
}
cs



Kotlin

'Kotlin' 카테고리의 다른 글

4. Delegated Property - Observable Property  (0) 2018.05.30
3. Lazy Initialization  (0) 2018.05.30
2. Java Static Method equivalent in Kotlin  (0) 2018.05.30