Kotlin/포스팅

코틀린 연산자 오버로딩

짜집퍼박사(짜박) 2024. 1. 3. 22:22

코틀린에서는 연산자 오버로딩을 지원하여 사용자가 자신만의 클래스에 대해 연산자를 새롭게 정의할 수 있습니다. 연산자 오버로딩을 사용하면 사용자 정의 타입에 대해 자연스럽게 연산을 수행할 수 있습니다.

다음은 코틀린에서 연산자 오버로딩을 어떻게 수행하는지에 대한 간단한 설명입니다.

 

1. 이항 연산자 오버로딩

이항 연산자를 오버로딩하려면, 해당 연산자에 대한 함수를 클래스 내부에 정의해야 합니다. 예를 들어, 두 개의 복소수를 더하는 plus 연산자를 정의하는 클래스를 살펴봅시다.

data class Complex(val real: Double, val imaginary: Double) {
    // 이항 덧셈 연산자 오버로딩
    operator fun plus(other: Complex): Complex {
        return Complex(real + other.real, imaginary + other.imaginary)
    }
}

fun main() {
    val c1 = Complex(1.0, 2.0)
    val c2 = Complex(3.0, 4.0)
    
    val result = c1 + c2 // 이항 덧셈 연산자 사용
    println(result) // 출력: Complex(real=4.0, imaginary=6.0)
}

 

2. 단항 연산자 오버로딩

단항 연산자를 오버로딩하려면 해당 연산자에 대한 함수를 클래스 내부에 정의합니다. 예를 들어, 복소수에 대한 단항 - 연산자를 정의하는 클래스를 살펴봅시다.

data class Complex(val real: Double, val imaginary: Double) {
    // 단항 마이너스 연산자 오버로딩
    operator fun unaryMinus(): Complex {
        return Complex(-real, -imaginary)
    }
}

fun main() {
    val c1 = Complex(1.0, 2.0)
    
    val result = -c1 // 단항 마이너스 연산자 사용
    println(result) // 출력: Complex(real=-1.0, imaginary=-2.0)
}

 

3. 대입 연산자 오버로딩

대입 연산자를 오버로딩하려면 plusAssign, minusAssign 등의 함수를 정의합니다.

data class Complex(var real: Double, var imaginary: Double) {
    // 복합 덧셈 대입 연산자 오버로딩
    operator fun plusAssign(other: Complex) {
        real += other.real
        imaginary += other.imaginary
    }
}

fun main() {
    var c1 = Complex(1.0, 2.0)
    val c2 = Complex(3.0, 4.0)
    
    c1 += c2 // 복합 덧셈 대입 연산자 사용
    println(c1) // 출력: Complex(real=4.0, imaginary=6.0)
}

 

4. 그 외의 연산자 오버로딩

다양한 연산자들을 오버로딩할 수 있습니다. 예를 들어, times 연산자, div 연산자 등이 있습니다.

data class Complex(val real: Double, val imaginary: Double) {
    // 곱셈 연산자 오버로딩
    operator fun times(other: Complex): Complex {
        val realPart = real * other.real - imaginary * other.imaginary
        val imaginaryPart = real * other.imaginary + imaginary * other.real
        return Complex(realPart, imaginaryPart)
    }
}

fun main() {
    val c1 = Complex(1.0, 2.0)
    val c2 = Complex(3.0, 4.0)
    
    val result = c1 * c2 // 곱셈 연산자 사용
    println(result) // 출력: Complex(real=-5.0, imaginary=10.0)
}

이와 같이 여러 연산자를 오버로딩하여 사용자가 정의한 클래스에 자연스럽게 연산을 수행할 수 있습니다. 코틀린에서는 다양한 연산자들에 대한 오버로딩이 가능하며, 이를 통해 코드의 가독성을 높일 수 있습니다.

 

With ChatGPT

'Kotlin > 포스팅' 카테고리의 다른 글

코틀린 증가와 감소  (0) 2024.01.03
코틀린 단항 연산  (0) 2024.01.03
코틀린 리플렉션 호출 가능  (0) 2024.01.03
코틀린 리플렉션 지정자와 타입  (0) 2024.01.03
코틀린 리플렉션 API  (0) 2024.01.03