Search code examples
kotlinextension-methods

Can I add Kotlin extension function to Java class?


I'm trying to create extension function like this:

fun UHFTAGInfo.toReadUhfTagInfo(): ReadUhfTagInfo {
    return ReadUhfTagInfo(this.epc, this.count, this.rssi.toIntOrNull())
}

It is supposed to convert UHFTAGInfo (from java library) to ReadUhfTagInfo (my class in Kotlin).

I'm trying to use it like this:

UHFTAGInfo i = getUHFTAGInfo();
ReadUhfTagInfo ri = i.toReadUhfTagInfo();

At this moment my toReadUhfTagInfo function is at top level, but finally I want to put it in my ReadUhfTagInfo class, like this:

class ReadUhfTagInfo(var epc: String, var cnt: Int, var rssi: Int?)
{
    fun UHFTAGInfo.toReadUhfTagInfo(): ReadUhfTagInfo {
        return ReadUhfTagInfo(this.epc, this.count, this.rssi.toIntOrNull())
    }
}

Solution

  • You can call Kotlin extension functions from Java, sure, but you can't call them with extension function syntax, you must call them like static methods. If you, for example, define

    // file: Foo.kt
    
    fun Bar.baz() { ... }
    

    then in Java, you would call this as

    FooKt.baz(bar);