Kotlin abstract class with generic param and methods which use type param

后端 未结 4 1623
情书的邮戳
情书的邮戳 2021-01-11 13:15

I\'m trying to create an abstract class with generic parameter which will have subclasses which should call methods without having to specify type parameters

4条回答
  •  盖世英雄少女心
    2021-01-11 13:54

    You cannot use a class' generic parameter as a reified generic (getting its T::class token), because at runtime the generic parameter is erased: Kotlin follows Java's type erasure practice and doesn't have reified generics for classes.
    (Kotlin has reified generics only for inline functions)

    Given that, it's up to you to pass and store a Class token so that you can use it.

    Also, myFunction in your example introduces a generic parameter, and it will be a new generic, not connected to the class generic parameter in any way (naming both T only adds confusion, consider them T1 and T2). If I get it right, you meant the class' generic instead.

    Probably what you can do is declare an abstract val that would store a class token and rewrite the function so that it uses the stored class token:

    abstract class AbstractClass constructor(protected val delegate: MyService) {
        protected abstract val classToken: Class
    
        fun myMethod(param: Any): T? {
            return delegate.myMethod(param).`as`(classToken)
        }
    }
    

    Then, deriving from AbstractClass will require overriding the classToken:

    class TesterWork constructor(delegate: MyService) : AbstractClass(delegate) {
        override val classToken = Tester::class.java
    }
    

    After that, you will be able to call the function on TesterWork instance without specifying the generic parameter:

    val service: MyService = ...
    val t: Tester? = TesterWork(service).myMethod("test")
    

提交回复
热议问题