본문 바로가기

Study/Kotlin Study

[Kotlin] 공통 메소드

+ 항공대학교 김철기 교수님의 객체 지향 프로그래밍 과목 내용를 정리한 글입니다.

Kotlin.Any 클래스

코틀린 클래스 계층 구조의 최상위 클래스이다.

 

모든 클래스는 Any를 직간접적으로 상속한다.

 

상위 클래스를 명시하지 않으면 자동으로 Any가 상위 클래스가 된다.

 

Any 클래스의 정의는 다음과 같다.

open class Any {
    public open operator fun equals(other: Any?)
    public open fun hashCode():Int
    public open toString(): String
}

equal() 함수

구조적 동등성 (==, !=)을 정의한다.

< equal() 정의 x >

open class Address(val city: String, val street: String, val house: String)

fun main() {
    val addr1 = Address("Seoul", "Mapodae-ro", "5")
    val addr2 = Address("Seoul", "Mapodae-ro", "5")

    println(addr1 == addr2) // False
}

 

< equal() 정의 >

open class Address(val city: String, val street: String, val house: String) {
    override fun equals(other: Any?): Boolean {
        if(other !is Address) return false
        if(city == other.city && street == other.street && house == other.house) return true
        return false
    }
}

fun main() {
    val addr1 = Address("Seoul", "Mapodae-ro", "5")
    val addr2 = Address("Seoul", "Mapodae-ro", "5")

    println(addr1 == addr2) // true
    println(addr1 === addr2) // false (참조 동등성 검사)
}

hashCode() 함수

Hashset, HashMap 등과 같은 집단 묶음을 만들 때 객체들을 구별하기 위한 hashCode 함수를 구현한다.

- 의미적으로 같은 객체(equals()가 동등하다고 판단하는 객체)는 같은 hashCode를 반환해야 한다.

open class Address(val city: String, val street: String, val house: String) {
    override fun equals(other: Any?): Boolean {
        if(other !is Address) return false
        if(city == other.city && street == other.street && house == other.house) return true
        return false
    }

    override fun hashCode(): Int {
        // 해쉬 코드를 만드는 기본 형식
        var code = city.hashCode()
        code = 31 * code + street.hashCode()
        code = 31 * code + house.hashCode()
        return code
    }
}

fun main() {
    val addr1 = Address("Seoul", "Mapodae-ro", "5")
    val addr2 = Address("Seoul", "Mapodae-ro", "5")

    println(addr1 == addr2)

    // 같은 해쉬 코드 반환
    println(addr1.hashCode())
    println(addr2.hashCode())

    val set = HashSet<Address>()
    set.add(addr1)
    println(addr2 in set) // true
}

toString() 함수

인스턴스의 기본 문자열 표현을 제공한다

 

< toString() 정의 x >

open class Address(val city: String, val street: String, val house: String) {
    override fun equals(other: Any?): Boolean {
        if(other !is Address) return false
        if(city == other.city && street == other.street && house == other.house) return true
        return false
    }

    override fun hashCode(): Int {
        var code = city.hashCode()
        code = 31 * code + street.hashCode()
        code = 31 * code + house.hashCode()
        return code
    }
}

fun main() {
    val addr1 = Address("Seoul", "Mapodae-ro", "5")
    val addr2 = Address("Seoul", "Mapodae-ro", "5")

    // toString()이 정의 되지 않을 때: 객체 위치와 hashcode 반환
    println(addr1) // kr.kau.main.Address@6f9cf654
    println(addr2) // kr.kau.main.Address@6f9cf654
}

 

< toString() 정의 >

open class Address(val city: String, val street: String, val house: String) {
    override fun equals(other: Any?): Boolean {
        if(other !is Address) return false
        if(city == other.city && street == other.street && house == other.house) return true
        return false
    }

    override fun hashCode(): Int {
        // 해쉬 코드를 만드는 기본 형식
        var code = city.hashCode()
        code = 31 * code + street.hashCode()
        code = 31 * code + house.hashCode()
        return code
    }

    override fun toString(): String {
        return "$city, $street, $house"
    }
}

fun main() {
    val addr1 = Address("Seoul", "Mapodae-ro", "5")
    val addr2 = Address("Seoul", "Mapodae-ro", "5")

    println(addr1) // Seoul, Mapodae-ro, 5
    println(addr2) // Seoul, Mapodae-ro, 5
}

'Study > Kotlin Study' 카테고리의 다른 글

[Kotlin] 인터페이스  (3) 2023.11.02
[Kotlin] 추상 클래스와 추상 멤버  (0) 2023.11.02
[Kotlin] 타입 검사와 캐스팅  (2) 2023.10.23
[Kotlin] 하위 클래스 초기화  (0) 2023.10.23
[Kotlin] 하위 클래스 선언  (2) 2023.10.23