I have two Kotlin extension methods for the same class, but with a different generic signatures and the compiler complains

前端 未结 1 503
暗喜
暗喜 2021-02-01 20:21

I am writing two extension functions for the same class:

class Something { ... }

They lo

相关标签:
1条回答
  • 2021-02-01 20:32

    Kotlin has the @JvmName annotation specifically for this type of use case. In Kotlin, there isn't a problem because it knows the difference between the methods. But the Java compatible byte code would have a conflict for naming since the generics erased signatures would be identical.

    Therefore you need to use this annotation to control the name from the perspective of Java and the JVM. Your Kotlin code will not see this alternative name and will use the name as you intended.

    Change your code to:

    @JvmName("somethingIntToJson") fun Something<Int>.toJson(): String = ...
    @JvmName("somethingDoubleToJson") fun Something<Double>.toJson(): String = ...
    

    From Kotlin, use normally:

    val someIntyThing = Something<Int>(194)
    val json = someIntyThing.toJson()
    
    0 讨论(0)
提交回复
热议问题