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

后端 未结 4 1584
情书的邮戳
情书的邮戳 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:58

    You can give the abstract class a casting lambda:

    abstract class AbstractClass(val delegate: MyService, val castFn: (Any) -> T) {
        fun myMethod(param: Any): T? {
            return castFn(delegate.myMethod(param))
        }
    }
    
    class TesterWork(delegate: MyService) : AbstractClass(delegate, {it as Tester}) {
    
    }
    

    You could maybe also make the class non-abstract, give it an interface and let an inline function create it:

    interface Inter {
        fun myMethod(param: Any): T
    }
    
    class NotAbstractClass(val delegate: MyService, val castFn: (Any) -> T) : Inter {
        override fun myMethod(param: Any): T {
            return castFn(delegate.myMethod(param))
        }
    }
    
    inline fun  makeClass(delegate: MyService): Inter {
        return NotAbstractClass(delegate, { it as T })
    }
    

    Then you can delegate like this:

    class TesterWork(delegate: MyService) : Inter by makeClass(delegate)
    
    val service: MyService = MyService()
    val t: Tester? = TesterWork(service).myMethod("test")
    

提交回复
热议问题