Search code examples
intellij-ideakotlinintellij-14

Compile error calling an extension method from another extension method in Kotlin


When I try to call an extension method from another extension method (overloading that method) it does not compile in IntelliJ 14.1.5 and Kotlin 0.14.449

As I'm new to the language and in the reference it does not forbid to do so I would like to know:

  • Is possible to call an extension method from another extension method?
  • Is the syntax I'm using correct (and thus this is a bug)?
  • If not, what is the correct syntax?

This is the code that does not compile:

fun String.replace (prefix: String, suffix: String, vararg parameters: Pair<String, String>) =
    parameters.fold(this, { result, pair -> result.replace (prefix + pair.first + suffix, pair.second) })

fun String.replace (vararg parameters: Pair<String, String>) =
    this.replace ("", "", parameters)

Thanks in advance!


Solution

  • As I though It was a bug, I searched into the Kotlin issue tracker and found this: https://youtrack.jetbrains.com/issue/KT-2079

    The correct syntax to pass a vararg argument to another function is using an asterisk '*':

    fun String.filter (prefix: String, suffix: String, vararg parameters: Pair<String, String>) =
        parameters.fold(this, { result, pair -> result.replace (prefix + pair.first + suffix, pair.second) })
    
    fun String.filter (vararg parameters: Pair<String, String>) =
        this.filter("", "", *parameters)