Renaming generated functions
In this recipe, we are going to learn how to modify a Kotlin function's name when it is being compiled to the generated JVM bytecode. We need this feature because of the type-erasure that happens when generating the JVM bytecode. However, thanks to the @JvmName
annotation, we can declare a number of different functions, but that has the same name and use their original name in the Kotlin code while keeping their JVM bytecode names distinct to satisfy the compiler.
How to do it...
- Declare two functions that have the same names:
fun List<String>.join(): String { return joinToString() } fun List<Int>.join(): String = map { it.toString() } .joinToString()
- Mark the functions with the proper annotations:
@JvmName("joinStringList") fun List<String>.join(): String { return joinToString() } @JvmName("joinIntList") fun List<Int>.join(): String = map { it.toString() } .joinToString()
How it works...
Thanks to providing the alternative function names...