Kotlin

연산자 함수, 오버로딩

kakaroo 2022. 5. 5. 10:28
반응형

article logo

 

코틀린에서는 연산자(단항 연산자, 증감 연산자, 산순연산자, in 연산자, 인덱스 접근 연산자, 호출 연산자, 복합 대입 연산자, 논리 연산자, 비교 연산자 등)마다 대응하는 함수가 있습니다. 

연산자 대응하는 메소드 주의사항
+x x.unaryPlus()  
-x x.unaryMinus()  
!x x.not()  
x + y x.plus(y)  
x - y x.minus(y)  
x * y x.times(y)  
x / y x.div(y)  
x % y x.rem(y)  
++x x.inc() x는 할당 가능해야 함
x++  x.inc() x는 할당 가능해야 함
--x x.dec() x는 할당 가능해야 함
x-- x.dec() x는 할당 가능해야 함
x == y x.equals(y)  
x != y  !(x.equals(y))  
x < y x.compareTo(y) <=, >, >= 도 사용 가능
x[i] x.get(i)  
x[i] = y x.set(i, y)  
y in x x.contains(y) !in 으로도 사용 가능
x..y x.rangeTo(y)  
x() x.invoke()  
x(y)
x.invoke(y)  
+=, -=, *=, /=, %= {method}Assign()  

 

목적에 따라 연산자를 클래스내에서 재정의(overloading)하여 사용이 가능합니다.

class Test {
    operator fun plus(b: Int) : Int {
        println("operator called")
        return b*2
    }
}

val test = Test()
print(test + 5)	// 10 출력

 

 

실제 사용 예) invoke 함수 오버로딩을 통한 Factory method 패턴

>> invoke 함수는 () 연산자입니다.

data class Price private constructor(val value: Int) {
    companion object {
        operator fun invoke(): Price {
            return Price(100)
        }
        operator fun invoke(value: Int): Price {
            return Price(value)
        }
    }
}

 

val a = Price(500)
println("a = $a") // 결과 : a = Price(value=500)

val b = Price()
println("b = $b") // 결과 : b = Price(value=100)
반응형

'Kotlin' 카테고리의 다른 글

제네릭  (0) 2022.05.08
data class  (0) 2022.05.06
위임자 Delegates (observable, vetoable )  (0) 2022.05.05
전개 연산자 *  (0) 2022.05.05
생성자 (constructor)  (0) 2022.04.30