Why not provide self-type for mixin interface?

In Scala, for a trait, it provides self-type. For example,

interface MyInterface {

this : HostClassType →

fun method(…) {
this.hostMethod(…)
}

}

Self type was considered, but didn’t get into the final language design. This thread might shed some light on why it happened.

1 Like

It’s funny that you would say that :slight_smile:

To quote:

Unfortunately, self-types are very hard to implement in the language without crippling the rest of the type system significantly

Andrey’s answers sometimes make me feel like I really should have attended more classes about compilers and language design back at university. I haven’t decided yet if that’s a bad thing, though.

At least, the rest discussion gives a little background on why you would want that kind of feature.

If Kotlin is a weak-type language like JavaScript, the life would be easy for FP. Unfortunately, Kotlin is based upon Java; as such, I think the type might matter for mixin.

There might be some valid scenarios that a mixin trait should be mixed with a specific type. With self type, the trait can have a better interaction with its target type. For example, some traits are specific to human beings and they should not the mixed with cats and dogs.

To clarify: the concept of the self-type in Scala is a bit different from what was discussed in that thread. Also, Scala’s approach is, AFAIU, based on dependent types, that a one of the hardest parts of Scala’s type system, and I’d avoid adding them to Kotlin.

1 Like