Kotlin은 사칙연산 (+, -, *, /)등을 오버로딩 해서 사용자의 입맛대로 변경할수 있도록 제공하고 있다.
File 명 : OperatorExample.kt
/**
* plus, minus, times, div(사칙연산)의 기능을 재정의 하기 위해선
* operator 키워드를 붙여줘야한다.
**/
class Point(var x: Int = 0, var y: Int = 0) {
operator fun plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
operator fun minus(other: Point): Point {
return Point(x - other.x, y - other.y)
}
operator fun times(other: Point): Point {
return Point(x * other.x, y * other.y)
}
operator fun div(other: Point): Point {
return Point(x / other.x, y / other.y)
}
fun print(){
println("x: $x, y: $y")
}
}
fun main(args:Array<String>){
val currentPoint:Point = Point(1,1)
val movePoint:Point = Point(4,3)
//Operator 사용법 1
val plusDstPoint = currentPoint + movePoint
val minusDstPoint = currentPoint - movePoint
val timesDstPoint = currentPoint * movePoint
val divDstPoint = currentPoint / movePoint
plusDstPoint.print()
minusDstPoint.print()
timesDstPoint.print()
divDstPoint.print()
println()
//Operator 사용법 2
val plusDstPoint2 = currentPoint.plus(movePoint)
val minusDstPoint2 = currentPoint.minus(movePoint)
val timesDstPoint2 = currentPoint.times(movePoint)
val divDstPoint2 = currentPoint.div(movePoint)
plusDstPoint2.print()
minusDstPoint2.print()
timesDstPoint2.print()
divDstPoint2.print()
}
[Kotlin] 생성자(Constructor) (0) | 2020.09.24 |
---|---|
[Kotlin] 초기화 (init) (0) | 2020.09.24 |
[Kotlin] 상속(Inheritance) (0) | 2020.09.24 |
[Kotlin] Getter & Setter (0) | 2020.09.24 |
[Kotlin] 변수, 상수, 타입 (0) | 2020.06.10 |