Home >Java >Using kotlin methods with value classes in Java code signing

Using kotlin methods with value classes in Java code signing

WBOY
WBOYforward
2024-02-09 08:51:22655browse

Using Kotlin methods with value classes in Java code signing is a common development technique. Value classes are a special type in Kotlin that can be used to store and pass data, similar to basic data types in Java. By using Kotlin methods with value classes in Java code, we can take full advantage of Kotlin's syntactic sugar and functional programming features to handle data in a concise and elegant way. In this article, we will introduce how to use Kotlin methods with value classes in Java code and explore its advantages and considerations. Whether you are a Java developer or a Kotlin enthusiast, this article will bring you valuable knowledge and tips.

Question content

I have such a kotlin entity

value class entityid(val id: long) {}

And some service interfaces

interface service() {
    fun do(entityid: entityid)
}

and its implementation.

But when I use the interface from java code like below

{
    ...
    entityid id = new entityid(1l);
    service.do(id) // service is interface here 
}

I'm getting a compilation error. But this is very understandable behavior because the kotlin compiler generates fun do(entityid: long) from the source code. Okay, let's use something like service.do(1l). Another question will appear:

java: cannot find symbol
symbol:   method do(long)

I guess this is because the interface doesn't actually change during compilation. I found a way - replace value class with data class but I will have value class.

Perhaps, is there some solution for this situation?

Workaround

You can overload a function that takes value class with a function that takes long and call the original function in the background. Note the value class overload on @jvmname so that java will only see the long overload.

Kotlin

@jvminline
value class entityid(val id: long)

class service {
    @jvmname("processentity")
    fun process(entityid: entityid) {        
    }

    fun process(entityid: long) {
        process(entityid(entityid))
    }
}

You can then call it from java using the long literal:

service.process(42L);

The above is the detailed content of Using kotlin methods with value classes in Java code signing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete