How do I call extension methods from outside the class they are defined in?

后端 未结 3 1979
死守一世寂寞
死守一世寂寞 2020-12-11 02:20

Here is a minimal example that demonstrates the problem:

abstract class Base {
    abstract fun String.extension(x: Char)
}

class Derived : Base() {
    ove         


        
3条回答
  •  悲哀的现实
    2020-12-11 02:56

    Your extension function is defined only inside of Base/Derived class. See Declaring Extensions as Members.

    abstract class Base {
        abstract fun String.extension(x: Char)
    }
    
    class Derived : Base() {
        override fun String.extension(x: Char) {
            // Calling lots of methods on String, hence extension method
            println("${first()} $length ${last()} ${firstOrNull { it == x }} ...")
        }
    
        fun callExtension(c: Char) {
            "hello".extension(c)
        }
    }
    
    fun main(args: Array) {
        val base = Derived()
        base.callExtension('h')
    }
    

提交回复
热议问题