How to overcome “same JVM signature” error when implementing a Java interface?

后端 未结 9 1826
星月不相逢
星月不相逢 2020-12-13 16:55

With the code below, I am getting the following error in IntelliJ IDEA 13.1.6 and Kotlin plugin 0.11.91.AndroidStudio.3:

Platform declaration clash: The foll         


        
相关标签:
9条回答
  • 2020-12-13 17:38

    You could use @JvmField for instructs the compiler not generate getter/setter, and you can implement your setters and getters. With this your code work well in Java (as attribute getter/setter) and Kotlin as property

    Example: JAVA:

    public interface Identifiable<ID extends Serializable> 
    {
       ID getId();
    } 
    

    KOTLIN:

    class IdentifiableImpl(@JvmField var id: String) :Identifiable<String> 
    {
       override fun getId(): String 
       {
           TODO("not implemented")
       }
    }
    
    0 讨论(0)
  • 2020-12-13 17:39

    Another work-around is to declare the properties in an abstract Kotlin class, then write a small java class that extends KotlinClass and implements JavaInterface.

    // JavaInterface.java
    public interface JavaInterface {
        int getFoo();
        void setFoo(int value);
    }
    
    // KotlinClass.kt
    abstract class KotlinClass(open var foo : Int = 0) {
    }
    
    // JavaAdapter.java
    class JavaAdapter extends KotlinClass implements JavaInterface {
        // all code in KotlinClass, but can't implement JavaInterface there
        // because kotlin properties cannot override java methods.
    }
    
    0 讨论(0)
  • 2020-12-13 17:40

    IMHO most readable combination is field + explicit interface implementation by the single-expression function (combination of @Renato Garcia's and @Steven Spungin's answers):

    Java:

    public inteface SomeInterface {
        String getFoo();
    }
    

    Kotlin:

    class Implementation(@JvmField val foo: String) : SomeInterface {
        override fun getFoo() = foo
    }
    
    0 讨论(0)
  • 2020-12-13 17:47

    The annotation feature of Kotlin named @JvmName will solve the duplication problem in Java and Kotlin when having the same signature.

    fun function(p: String) {
       // ...
    }
    
    // Signature: function(Ljava/lang/String)
    

    With the use of JvmName will be:

    @JvmName("functionOfKotlin")
    fun function(p: String) {
       // ...
    }
    
    // Signature: functionOfKotlin(Ljava/lang/String)
    
    0 讨论(0)
  • 2020-12-13 17:48
    public interface JavaInterface {
        public String getName();
    }
    
    public class KotlinClass(val namePrivate: String?) : JavaInterface {
    
    private var name = namePrivate
    
        override fun getName(): String? {
            return name
        }
    }
    
    0 讨论(0)
  • 2020-12-13 17:48

    Rename the variable to something else, or make it private if u dont want it to be public.

    0 讨论(0)
提交回复
热议问题