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

后端 未结 3 1983
死守一世寂寞
死守一世寂寞 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:52

    To decale an extension method outside the class using it, you should NOT implement it inside a class, and you should do like this:

    package com.sample.test
    
    import java.io.File
    
    fun File.folderLength() : Long {
        return 0L
    }
    

    So in your class that call this method:

    package com.sample.util
    
    import com.sample.test.*
    import java.io.File
    
    class foo{
        fun getFolderSize(url: String) : Long{
            var file = new File("...")
            var length = file.folderLength()
            return length
        }
    }
    

    Hope this should help you.

提交回复
热议问题