Collision with Kotlin extension

If I have a jar, on the way to the classes where I created an extension function, for example, for the String class for an argument, and I have another jar with the same extension function on String, how does Kotlin allow two?

I assume that if both functions are defined in the same packages, will a collision occur?

But if there are different packages, how can I distinguish between two extensions?

+5
source share
2 answers

Indeed, if they are in the same package, it will not compile. For another scenario, suppose you have two files with two different packages containing extension functions with the same signature:

First file:

package ext1 fun Int.print() = print(this) 

Second file:

 package ext2 fun Int.print() = print(this * 2) 

And this file in which you are trying to use it:

 package main fun main(args: Array<String>) { 42.print() } 

IntelliJ will actually provide you with an import dialog box in which you can choose which one you want to use:

enter image description here

You can import one of them as follows:

 import ext1.print 

And if you need to use another one, you can rename it with the as keyword. This keyword works for importing in general, classes with the same name, etc.

 import ext2.print as print2 

So, this program compiles and prints 4284 :

 package main import ext1.print import ext2.print as print2 fun main(args: Array<String>) { 42.print() 42.print2() } 

As a brief note, it will be more difficult for you to use the one you import with the as keyword, since autocomplete does not seem to pick it very well, selecting the second option completes the 42.print() call.

enter image description here

+13
source

So, since the extension function in kotlin is only a static function, other functions will be different when imported.

You can also make an alias for one of the extension functions for greater readability:

 import by.bkug.extensions.helpers.extension import by.bkug.extensions.extension as extension1 fun test() { myType().extension() // by.bkug.extensions.helpers.extension myType().extention1() // by.bkug.extensions.extension } 
+3
source

Source: https://habr.com/ru/post/1265360/


All Articles