Kotlin 运算符重载
2020/4/30 23:02:41
本文主要是介绍Kotlin 运算符重载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
kotlin运算符重载的范围
java是不支持任何运算符重载的,但是kotlin支持,这里要注意的是kotlin支持的运算符重载也是有限的,不像c++ 的重载那么强大灵活。
可以去官网查看支持哪些运算符的重载
其中出镜率最高的几个,我们总结一下
==与equals , +与plus ,in与contains ,[]与get , >与compareto , ()与invoke
重载运算符的实例
定义一个复数类
//复数 class Complex(var real: Double, var image: Double) { override fun toString(): String { return "$real+${image}i" } } 复制代码
然后我们对他进行一些运算符重载。
operator fun Complex.plus(other: Complex): Complex { return Complex(this.real + other.real, this.image + other.image) } operator fun Complex.plus(other: Double): Complex { return Complex(this.real + other, this.image) } operator fun Complex.plus(other: Int): Complex { return Complex(this.real + other, this.image) } operator fun Complex.minus(real: Double): Complex { return Complex(this.real - real, this.image) } //0 返回虚部 1实部 operator fun Complex.get(index:Int):Double{ return when(index){ 0 -> this.real 1 -> this.image else -> throw IndexOutOfBoundsException() } } 复制代码
然后看看他的使用
fun main() { val c = Complex(1.0, 2.0) println(c) val c1=Complex(3.0,4.0) val c2=Complex(2.0,2.0) println(c1+c2) println(c1+3) println(c1+2.0) println(c1-1.0) println(c1[1]) println(c1[0]) } 复制代码
结果
![](/upload/202004/30/202004302302409343.png)
通过这个例子 你应该能看出来,kotlin的运算符重载最大的作用就是增加这门语言的表达力
中缀表达式
看个最简单的例子,应该有人知道 to的作用吧。
![](/upload/202004/30/202004302302409812.png)
那这个to 本质上是啥?
实际上他就等价于
println(2.to(3)) 复制代码
我们看一下源码:
![](/upload/202004/30/202004302302410017.png)
这个infix 关键字 就是告诉编译器 可以 用 2 to 3 的这种简写方式了。
比如 我们想 逆序一个字符串
//index 为分割线 分割一个字符串 infix fun String.rotate(count: Int): String { val index = count % length return this.substring(index) + this.substring(0, index) } 复制代码
fun main() { println("helloworld" rotate 5) println("helloworld".rotate(5)) } 复制代码
看下结果;
![](/upload/202004/30/202004302302410281.png)
和 to的 写法 其实就是一样的了。 不加infix的话 就不可以用简写的方式了
中缀表达式 在 kotlin dsl中 很常见,一定要掌握。
kotlin 中 空安全要额外注意的地方
![](/upload/202004/30/202004302302411013.png)
![](/upload/202004/30/202004302302412673.png)
kotlin中的 空类型继承关系
![](/upload/202004/30/202004302302413874.png)
智能类型转换的建议写法
![](/upload/202004/30/202004302302414245.png)
这篇关于Kotlin 运算符重载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-01-18android.permission.read_media_video
- 2024-01-18android_getaddrinfo failed eai_nodata
- 2024-01-18androidmo
- 2024-01-15Android下三种离屏渲染技术
- 2024-01-09Android 蓝牙使用
- 2024-01-06Android对接华为AI - 文本识别
- 2023-11-15代码安全之代码混淆及加固(Android)
- 2023-11-10简述Android语音播报TTS
- 2023-11-06Android WiFi工具类
- 2023-07-22Android开发未来的出路