在Kotlin中,運算符重載允許你為自定義類型(如類或結構體)定義新的運算符行為。處理復雜運算時,可以通過擴展運算符函數來實現。以下是一些示例,展示了如何在Kotlin中處理復雜運算:
data class Point(val x: Int, val y: Int)
fun Point.plus(other: Point): Point {
return Point(x + other.x, y + other.y)
}
fun main() {
val p1 = Point(1, 2)
val p2 = Point(3, 4)
val result = p1 + p2
println("Result: (${result.x}, ${result.y})") // 輸出 "Result: (4, 6)"
}
data class Person(val name: String, val age: Int)
fun Person.compareTo(other: Person): Int {
return age.compareTo(other.age)
}
fun main() {
val person1 = Person("Alice", 30)
val person2 = Person("Bob", 25)
val comparisonResult = person1 compareTo person2
when (comparisonResult) {
-1 -> println("person1 is younger than person2")
0 -> println("person1 and person2 are the same age")
1 -> println("person1 is older than person2")
}
}
data class Fraction(val numerator: Int, val denominator: Int)
fun Fraction.toString(): String {
return "$numerator / $denominator"
}
fun main() {
val fraction = Fraction(3, 4)
println("Fraction: ${fraction.toString()}") // 輸出 "Fraction: 3 / 4"
}
在處理復雜運算時,可以根據需要為自定義類型定義更多的運算符函數。只要遵循Kotlin的運算符重載規則,就可以輕松地為自定義類型提供合適的運算符行為。