operator
关键字的函数。
通过添加 operator
修饰符,您可以允许函数的使用者编写更符合 Kotlin 习惯的代码。
示例:
class Complex(val real: Double, val imaginary: Double) {
fun plus(other: Complex) =
Complex(real + other.real, imaginary + other.imaginary)
}
fun usage(a: Complex, b: Complex) {
a.plus(b)
}
建议通过快速修复添加 operator
修饰符关键字:
class Complex(val real: Double, val imaginary: Double) {
operator fun plus(other: Complex) =
Complex(real + other.real, imaginary + other.imaginary)
}
fun usage(a: Complex, b: Complex) {
a + b
}