Kotlin 运算符
运算符重载
kotlin运算符重载,而java不支持
格式:
operator fun 参数1的类型 . 运算符函数 ( 参数2及其类型 ) : 返回值类型 {
...
}
如,自定义矩阵类 Matrix ,并让其支持 +
, -
, *
操作
class Matrix( val e: Array<Int> ) {
override fun toString(): String = e.toList().toString()
}
operator fun Matrix.plus(a2: Matrix): Matrix = Matrix( e.clone() ).apply {
// 矩阵加法计算过程
e.forEachIndexed{k, _ ->
e[k][email protected][k]+a2.e[k]
}
}
operator fun Matrix.minus(a2: Matrix): Matrix = Matrix( e.clone() ).apply {
// 矩阵减法计算过程
e.forEachIndexed{k, _ ->
e[k][email protected][k]+a2.e[k]
}
}
operator fun Matrix.times(a2: Matrix): Matrix = Matrix( e.clone() ).apply {
// 矩阵乘法计算过程
e.forEachIndexed{k, _ ->
e[k][email protected][k]*a2.e[k]
}
}
var a1 = Matrix( arrayOf(1,2,3) )
var a2 = Matrix( arrayOf(4,5,6) )
var a3 = a1 + a2
a3 = a1 - a2
a3 = a1 * a2
kotlin没有 &
, |
, <<
, >>
等按位运算符,取代的的 位运算 函数
函数 | 功能 | 等效的java运算 |
---|---|---|
and | 按位与 | & |
or | 按位或 | \ |
inv | 按位非 | ~ |
xor | 按位异或 | ^ |
shl | 左移 | << |
shr | 右移 | >> |
ushr | 无符号右移 | >> |