상세 컨텐츠

본문 제목

[Kotlin] Getter & Setter

Programming language/Kotlin

by choiDev 2020. 9. 24. 13:58

본문

코틀린은 기본적으로

Getter Setter가 프로퍼티에 포함되어있기 때문에

자바와 같이 Getter Setter를 선언할 필요가 없다.

 

1. Getter Setter 예제

class Person {
    var age: Int = 0
}

fun main(args: Array<String>) {
    val person:Person = Person()
    
    person.age = 3      //Setter
    println(person.age) //Getter
}

 

 

하지만 Setter랑 Getter에 로직이 들어가야 하는 경우 변경이 필요할 수도 있다 

그 방법은 아래와 같다.

 

2. Getter Setter 예제 1

File 명 : GetterSetterExample.kt

/**
 * jhChoi - 20200924
 * getter setter 구현 예제
 * */
class Apple {
    var count: Int = 0
        get() {
            return field
        }
        set(count) {
            field = if (count >= 0) count else 0
        }

    fun print() {
        println(count)
    }
}

fun main(args: Array<String>) {
    val apple: Apple = Apple()

    //Setter 조건식에 맞지 않는 값을 대입
    apple.count = -1
    apple.print()

    //Setter 조건식에 맞는 값을 대입
    apple.count = 99
    apple.print()
}

[실행 결과]

0
99

 

File 명 : GetterSetterExample2.kt

3. Getter Setter 예제 2 ( []를 사용해서 Getter, Setter를 하는 예제 입니다.)

class Computer(var name: String = "", var price: String = "") {
    operator fun get(position: Int): String {
        return when (position) {
            0 -> name
            1 -> price
            else -> "알수없음"
        }
    }

    operator fun set(position: Int, value: String) {
        when (position) {
            0 -> name = value
            1 -> price = value
        }
    }
}

fun main(args: Array<String>) {
    val com1: Computer = Computer()

    com1[0] = "mac"
    com1[1] = "1000000"

    println(com1[0])
    println(com1[1])
}

[실행 결과]

mac
1000000

관련글 더보기