equal 비교 연산 > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

Android | equal 비교 연산

본문

==

값이 동일한지

 

===

값과 주소가 동일한지

 

모든 객체는 Any 클래스를 상속받았으며 Any 에는 equal() 메소드가 있기 때문에 값의 비교가 가능하다.

사용자정의 클래스에서 equal 메소드를 override 하여 비교연산을 재정의 할 수 있다.

 

[code]

fun main() {

var a = Product("콜라", 1000)

    var b = Product("콜라", 1000)

    var c = a

    var d = Product("사이다", 1000)

    

    

    println(a == b)

    println(a === b)

    println(a == c)

    println(a === c)

    println(a == d)

    println(a === d)

}


class Product(val name: String, val price: Int) {

    override fun equals(other: Any?): Boolean {

        if (other is Product)

        {

            return other.name == name && other.price == price

        }

        return false

    }

}

[code]

 

결과

[code]

true

false

true

true

false

false

[/code]

댓글 0개

등록된 댓글이 없습니다.

Menu