Home > Software design >  Kotlin: Extension inside class
Kotlin: Extension inside class

Time:08-09

I have an extension function inside class

class Utils{
    private var x : Int = 0;

    public fun Utils.multiply() : Int{
        return this.x*100;
    }
}

Why I can use extension multiply inside another

fun Utils.add() : Int{
    return this.multiply() 100
}

But can not use in class Main

class Main{
    val utils = Utils()


    val multi = utils.multiply() //error : Unresolved reference
}

CodePudding user response:

When you declare an extension function inside a class, it's only accessible inside the class's scope. There's just no way to refer to it directly (at the moment anyway).

You can use a scope function to put yourself in that scope though:

val multi = utils.run { multiply() }

But you can only access public functions this way - if the extension function is private inside that class, you have to actually be running the code inside that class where the function is visible. Doing classWithPrivateStuff.run { superPrivateFunction() } won't get around those restrictions

  • Related