Search code examples
javafunctionkotlinuuid

Kotlin extensions does not work with java.util.UUID


I've tried to create extension function in Kotlin, however, compilator does not see it, it does not work, no matter if I import it manually or not, other extensions work well in my code. It event does not work if I put this extension in a class where I want to use it.

import java.nio.ByteBuffer
import java.util.*

fun UUID.fromDatabase(byteArray: ByteArray): UUID {
    val bb: ByteBuffer = ByteBuffer.wrap(byteArray)
    val high: Long = bb.getLong()
    val low: Long = bb.getLong()

    return UUID(high, low)
}

enter image description here

EDIT: I see that is not possible, to add static extension, I had to do something like below:

fun KClass<UUID>.fromDatabase(byteArray: ByteArray): UUID {
    val bb: ByteBuffer = ByteBuffer.wrap(byteArray)
    val high: Long = bb.getLong()
    val low: Long = bb.getLong()

    return UUID(high, low)
}

and the usage

val id = UUID::class.fromDatabase(element["id"] as ByteArray)

Solution

  • Your extension is on the UUID instance, that's why it's not working when called as a static method (but, for example, UUID.randomUUID().fromDatabase(...) would work)

    You would be able to do this if UUID class was written in Kotlin and had public companion object, so that your extension function would have been on UUID.Companion, but in this case it's impossible.