简体   繁体   中英

Extension function with different signature is confusing with different extension function in kotlin

class Example

fun main(){

    val example: Example = Example()

    // what function i am calling is it fun Example.extensionFun() ?
    // Or is it Example.extensionFun(string: String) ?
    example.extensionFun()

}

// first extension function
fun Example.extensionFun(){
   println("Hey i'm first extension function")
}

// second extension function
fun Example.extensionFun(testArgument: String = "test argument "){ // argument just to change the function signature
    println("Hey i'm second extension function ")
}

In the above example i have created two extension function with the same name but different signature. When i try to call ->

example.extensionFun()

then IDE just calls the "fun Example.extensionFun()"

but even if i try to call

fun  Example.extensionFun(testArgument: String ="test argument") 

在此处输入图片说明

by using code completion pop up and selecting second extension function it is again calling

fun Example.extensionFun()

and thus it left me single way to call the second extension function which is by passing the different value for the testArgumet (argument). for eg.

example.extensionFun("different value")

but there is many cases where we don't want to change the default value of the function parameter when we are calling it.

I think i found a bug but kindly please share your opinion

When it's ambiguous, the compiler calls the overload that has fewer arguments. In fact, I don't think it even generates overloads for function signatures that are already explicitly declared. They should probably provide a compiler warning to let you know the default value is pointless, but maybe that was deemed too expensive for compile times.

Your only option is to use a different function name to break the ambiguity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM