简体   繁体   中英

How do I import/use a generic overloaded operator function?

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 ?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM