简体   繁体   中英

Generics, companion object, and inheritance in kotlin

I'm working with ViewBindings on Android, with code generated by the compiler from the xml that must look like that

class ViewBinding {...}

class MyBinding : ViewBinding {
    companion object {
        fun inflate (...) { 
            ...
        }
    }
}

To avoid copy/pasting code, I want to create a class, accepting a class child of ViewBinding as a generic type argument, and with a companion object having the method inflate.

class MyClass<T:ViewBinding having the method inflate in the companion object of the class> { ... }

What's the smartest way to do that?

As it is, what you're trying to do is impossible. The type parameter restrictions apply on the type itself, not its companion object, which isn't actually related to the class (it gets compiled as a separate class with no relation with the original class). The Java equivalent, implementing a static method from an interface, also isn't possible.

What you could do however, is to use the companion itself as a type parameter, the companion implementing an interface with the inflate method:

interface ViewBindingCompanion {
    fun inflate(): ViewBinding
}

class MyBinding : ViewBinding {
    companion object : ViewBindingCompanion {
        fun inflate(): ViewBinding { 
            ...
        }
    }
}

class MyClass<T : ViewBindingCompanion>

And then:

MyClass<MyBinding.Companion>()

Leave a comment if I missed something.

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