Headache of inheritance of Kotinovsky generics

I am new to Kotlin and I am trying to compile this code without success (this is just an example of what I want to do in a real project):

abstract class Builder<T: Any, Y: Any> 

class BuilderImpl() : Builder<String, Int>()

abstract class Shape<T: Any>(){
     abstract var builder: Builder<T, *>
}

class Circle() : Shape<String>(){
     override var builder: Builder<String, Int> = BuilderImpl()
}

I want to override the builder property from the Shape class in the Circle class. The Shape class knows only the first generic type from the Builder class. The second can be any type, so I use * for this.

When I try to override the builder property in the Circle class, the compiler complains about the message:

  "Var-property type is 'Builder<String, Int>', which is not a type of overriden public abstract var builder: Builder<String, *>".

I also try with something like "out Any" instead of *, without success.

I do not know how to compile this code.

+4
source share
1 answer

var, ,

  • : S, S, S (, Int, Number);

  • : S, S , S (, String, Any )

, , var, , . , - Builder<T, *>, Builder<T, Int> :

val s: Shape<SomeType> = Circle<SomeType>()
val b: Builder<SomeType, *> = someBuilder

s.builder = b // should be type-safe, but won't be with the override you want to do

, var , Kotlin in out.

:

  • val. , :

    abstract class Shape<T: Any>(){
        abstract val builder: Builder<T, *>
    }
    
    class Circle() : Shape<String>(){
        override var builder: Builder<String, Int> = BuilderImpl() // OK
    }
    
  • . var, Circle Shape<String, Int>, Shape<T, R>:

    abstract class Shape<T: Any, R: Any>(){
        abstract var builder: Builder<T, R>
    }
    
    class Circle() : Shape<String, Int>(){
        override var builder: Builder<String, Int> = BuilderImpl() // OK
    }
    
+3

Source: https://habr.com/ru/post/1659550/


All Articles