Learn Kotlin Programming by Stephen Samuel

Learn Kotlin Programming by Stephen Samuel

Author:Stephen Samuel [Stephen Samuel]
Language: eng
Format: epub
Tags: COM051000 - COMPUTERS / Programming / General, COM051280 - COMPUTERS / Programming Languages / Java, COM051460 - COMPUTERS / Programming / Mobile Devices
Publisher: Packt Publishing
Published: 2019-05-29T09:10:58+00:00


@JvmName

Due to erasure in the JVM, it is impossible to declare two functions with the same name and the same erased signature. For example, the following declarations in Java would result in a compile error:

public void foo(list: List<String>) public void foo(list: List<Int>)

Erasure is caused by the fact that the JVM does not retain type parameters. This means, among other examples, that variables of List<String> and List<Int> both compile to List<Any>.

The most commonly used solution to this problem is to name methods differently. But sometimes that isn't desirable. In Kotlin, we can retain the same names as long as we provide alternative names for when they are compiled. To do this we annotate the functions using @JvmName with a supplied alternative, as the following examples show:

@JvmName("filterStrings") fun filter(list: List<String>): Unit @JvmName("filterInts") fun filter(list: List<Int>): Unit

At compile time the name supplied to the annotation will be used. We can see this by inspecting the generated bytecode:

public static final void filterStrings(java.util.List<java.lang.String>); Code: [ ... ] public static final void filterInts(java.util.List<java.lang.Integer>); Code: [ ... ]

When using these functions from Kotlin, we continue to use the original names. The @JvmName annotation is invisible to Kotlin users. The compiler will do the necessary translation for us, but when invoking these functions from Java we use the alternative name.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.