Kotlin extension clash

北城余情 提交于 2019-12-01 03:58:07

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().

So since extension function in kotlin is just static function, other functions will be distinguish by import.

Also you can make alias for one of extension functions for more 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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!