Lets say simple Type Parameter (like T
in class IceCream<T : Flavor>
) is different from Generic Type Parameter (like T
in class Producer<T: IceCream<*>>
) in the way that the latter implicitly holds type parameter in itself. So intuitively we may want to write something like that <T<*>: IceCream<*>>
. And in some languages (i.g. Scala) it’s possible, but presumably not in Kotlin. So the first question: Is it possible to implement this feature in Kotlin?
One usage example (the domain of sweets has just been chosen for fun… so i console myself
Lets say we have vast amount of ice cream types of different flavors. And we’re developing a Producer
abstraction that produces one specified type of ice cream of any flavor and than serves it in different ways, like extra frozen, or in a gift wrapper. And that’s how it would look like in Scala:
class Flavor
object Chocolate extends Flavor
class IceCream[F: Flavor](var temperature: Float = -1)
class Popsicle[F: Flavor] extends IceCream[F]
abstract class Producer[T[_] <: IceCream[_]] {
abstract def produce[F: Flavor](): T[F]
def serveFrozen[F: Flavor](): T[F] = {
val ic = produce[F]; ic.temperature = -100; ic
}
}
object ProducerImpl extends Producer[Popsicle] {
override def produce[F: Flavor](): Popsicle[F] = new Popsicle[F]
}
val popsicle: Popsicle[Chocolate.type ] = ProducerImpl.serveFrozen[Chocolate.type]()
The basic idea is to implement all service methods within an abstraction of Producer
. And let subclasses override only produce
method.
I’m afraid all i can do now about it in Kotlin is:
abstract class Producer<T: IceCream<*>> {
abstract fun produce(): T
}
that produces only ice cream with star <*> flavor… so i got no second question.
Please correct me if i’m not precise in terminology.