Using typealias on generics


#1

Hi
I attended the UGM in Munich yesterday, talking with Eugene later about a problem I can’t solve. He suggested to post it, maybe you have an idea…

For simplicity and readability I would like to get rid of the generic in the alias. But uncommenting the doThat does not compile.

fun main(args: Array<String>)
{
    val demo = Demo<String>()

    demo doThis { say("generic alias") }
//  demo doThat { say("simpler alias") }
}

typealias genericContext<T> = Demo<T>.() -> Unit
typealias simplerContext    = Demo<*>.() -> Unit

class Demo<T>
{
    infix fun doThis(block: genericContext<T>) = block()
    infix fun doThat(block: simplerContext   ) = block()

    fun say(obj: T) = println(obj.toString())
}

#2

I don’t fully understand your problem.

typealias simplerContext = Demo<*>.() -> Unit

leads to a compile error, because the Demo class does not take a type argument. What exactly are you trying to do?


#3

Ups…
I does -the editor has eaten the lace braces!

It should be:

typealias genericContext< T > = Demo<T>.() -> Unit
typealias simplerContext    = Demo<*>.() -> Unit

class Demo< T >
{
    infix fun doThis(block: genericContext< T >) = block()
    infix fun doThat(block: simplerContext   ) = block()

    fun say(obj: T) = println(obj.toString())
}

sorry


#4

So if I understand you correctly you want to have a type alias which looks something like this

typealias simplerContext = Demo<>.() -> Unit
or
typealias simplerContext = Demo.() -> Unit

but behaves like this one

typealias genericContext<T> = Demo<T>.() -> Unit

I don’t really see any way to achieve this.


#5

Your block runs in the context of a Demo<*>. It cannot call the say function because it receives an argument of type T, which is unknown.

https://kotlinlang.org/docs/reference/generics.html#star-projections

If T appears as a return type, the method is still usable, the type will be treated as if it were the upper bound (Any? in this case, I think).
If T appears as the argument of a method, the method becomes unusable.