I have a Kotlin class which is the base for other classes, and want to define an operator times to be used with its derived classes.
In Base.kt
abstract class Base<Q : Base<Q>> internal constructor(open protected val rawValue: Long)
: Comparable<Q> {
// allows Q * Double
operator fun times(factor: Double) = selfFactory(rawValue * factor)
// selfFactory instantiates an object of derived type Q
}
// Supposed to allow Double * Q
internal operator fun <Q : Base<Q>> Double.times(factor: Q) = factor * this
In Derived.kt
data class Derived internal constructor(override val rawValue: Long)
: Base<Derived>(rawValue) {
}
In some other file
import com.mycompany.Derived
fun foo(d: Derived): Derived = 5.0 * d; // doesn't find the operator
How can I import this generic operator to allow Double * Q?
CodePudding user response:
The operator is defined in Base.kt file.
So, assuming the base.kt file in located in the package com.mycompany you just need to import the operator times : com.mycompany.times
CodePudding user response:
Make sure the operator function returns Q, not Base<Q>. Otherwise, at your use site in foo(), it will be trying to return Base<Derived> instead of Derived, which is not necessarily the same thing.
Maybe it already does, but I don't know what selfFactory() looks like.
It's good practice to be explicit about declaring return types of public functions, even if you're using the = notation.
If your use site is not in the same package you defined the extension function in, you need to import it. You can hover the cursor over the * inside foo() if you want the IDE to offer to add the import for you.
You marked it internal so it will not be visible in other modules.
