科特林扩展冲突 [英] Kotlin extension clash
问题描述
如果我有一个jar,在类路径上,我为了参数而创建了一个扩展函数,比如String类,我在String上有另一个具有相同扩展函数的jar,Kotlin如何解析这两个? / p>
我认为如果两个函数都在相同的包中定义,那么会发生冲突吗?
但是如果不同的包,我怎么能区分这两个扩展?
实际上,如果它们在同一个包中,它将无法编译。对于另一种情况,假设您有两个包含两个不同包的文件,其中包含具有相同签名的扩展函数:
第一个文件:
package ext1
fun Int.print()= print(this)
第二档:
package ext2
fun Int.print()= print(this * 2)
这个文件在哪里'试图使用它:
package main
fun main(args:Array< String> ){
42.print()
}
IntelliJ实际上会给你导入对话框,您可以在其中选择要使用的对话框:
您可以像这样导入其中一个:
import ext1.print
如果您还需要使用另一个,可以使用重命名为
关键字。此关键字适用于一般的导入,具有相同名称的类等。
import ext2.print as print2
所以这个程序编译并打印 4284
:
package main
import ext1.print
import ext2.print as print2
fun main(args:Array< String>){
42.print()
42.print2()
}
作为快速说明,使用作为
关键字导入的关键字将稍微难以使用,因为自动完成似乎没有很好地选择它,在这里选择第二个选项只需完成对 42.print()
的调用。
If I have a jar, on the classpath, where I've created an extension function on say the String class for argument's sake and I have another jar with the same extension function on String, how will Kotlin resolve the two?
I presume if both functions are defined in the same packages then there will be a clash?
But if different packages, how I can distinguish the two extensions?
Indeed, if they're in the same package, it won't compile. For the other scenario, let's say 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 where you're trying to use it:
package main
fun main(args: Array<String>) {
42.print()
}
IntelliJ will actually give you an import dialog where you can choose which one you want to use:
You can import one of them like this:
import ext1.print
And if you need to use the other one as well, you can rename it with the as
keyword. This keyword works for imports 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 quick note, the one you import with the as
keyword will be slightly harder to use, as autocomplete doesn't seem to pick it up well, selecting the second option here just completes the call to 42.print()
.
这篇关于科特林扩展冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!