Tag: 运算符重载

如何在Kotlin的重载操作符上指定generics?

我正在寻找超载除法运算符“/”,但希望允许指定genericstypes来指导返回值的types。 这是一个例子: inline operator fun MyType.div(fieldName: String): T { val value = someFunction(fieldName) return convertToExpectedValue(value) } 不幸的是,我无法想出一个方法来明确指定genericstypesT,当它不能被推断。 我想知道是否有像以下这样的工作? val stringVal = myType / “myField” / “myStringField” 请注意,我知道这一点 myType.div(“blah”) 作品。 我正在寻找使用运算符“/”的东西。

在kotlin中,当我重载inc()运算符时,出现错误

以下代码显示Point对象上的unaryMinus函数的重载,该函数正常工作。 data class Point(val x: Int, val y: Int) operator fun Point.unaryMinus(): Point = Point(-x, -y) 与上面类似,重载inc()函数将导致错误。 operator fun Point.inc(): Point { return Point(this.x + 1, this.y + 1) } 错误内容如下。 错误:(29,4)Gradle:’operator’修饰符不适用于这个函数:receiver必须是返回types的超types 怎么了?

Kotlin中所需的运算符关键字是什么时候?

在第14次操作符重载的Kotlin Koan中 ,我惊讶地发现解决方案后,我看到了答案,并且看到compareTo方法不需要operator修饰符: data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable { override fun compareTo(other: MyDate) = when { year != other.year -> year – other.year month != other.month -> month – other.month else -> dayOfMonth – other.dayOfMonth } } 运营商重载的文档中明确指出: 超载操作符需要用运算符修饰符标记。 那么这里发生了什么? 为什么这个代码编译? 何时需要operator ?

Kotlin协程中的“+”?

这是通过 Kotlin Coroutines的显式工作取消示例代码: fun main(args: Array) = runBlocking { val job = Job() // create a job object to manage our lifecycle // now launch ten coroutines for a demo, each working for a different time val coroutines = List(10) { i -> // they are all children of our job object launch(coroutineContext + job) […]