Vojtěch
Vojtěch

Reputation: 12416

Kotlin generics and wrong type inference

Consider a general class Item and specific class Event which inherits it:

open class Item<T> {
    fun copyFrom(item: T) {
        if (this is Event && item is Event) {
            owner = item.owner
            value = item.value 
        }
    }
}

class Event : Item<Event> {
    open var owner = ""
    open var value = 0
}

Thanks to type inference we don't have to cast Item to Event and we can directly access the owner and value. However it says the item is of type T and cannot be cast to Event in the item is Event clause. I believe this should not happen as this clause is correct in Java?

EDIT:

I am aware of the fact that the copyFrom implementation should be done in Event, but this is just to demonstrate the type inference issue.

Upvotes: 1

Views: 177

Answers (1)

GhostCat
GhostCat

Reputation: 140613

Even when you sort out the syntactical problems: do not do this.

You are creating a generic container, which explicitly checks if a distinct subclass comes in. To then do a downcast and access fields in the subclass.

This is like the absolute opposite of a good OO design. You base class should know nothing about any subclass!

Upvotes: 4

Related Questions