https://kotlinlang.org logo
Title
a

Antanas A.

04/15/2019, 2:06 PM
Hi, Is it possible to have function which has two generic types and explicitly define only one type in call sites:
`
        suspend fun <T, U> DataSource.mustHave(block: suspend T.() -> U): U =
            ((this as? T) ?: throw RuntimeException("Operation is not supported")).block()
`
and use it:
dataSource.mustHave<DataSource.HasAddOperation> { add(command) }
Logically it should be able to infer U type automatically, but if I'm specifying first type T compiler requires me to specify also U type. eg.
dataSource.mustHave<DataSource.HasAddOperation, AddResult> { add(command) }
Is it possible to somehow declare that extension function in a way that U type be inferred automatically?
r

ribesg

04/15/2019, 2:13 PM
I don’t think you can have partial content in
<>
c

Czar

04/15/2019, 2:29 PM
Currently this is not possible in Kotlin, but I remember there was an issue or two on Youtrack, try searching for it. I don't remember what was the decision on this, but it was definitely discussed at some point.
p

Pavlo Liapota

04/15/2019, 2:36 PM
I would recommend:
fun <T> DataSource.mustHave(): T =
    (this as? T) ?: throw RuntimeException("Operation is not supported")
And then you can write
dataSource
.mustHave<DataSource.HasAddOperation>()
.add(command)
or following, if you want to call several methods:
dataSource
.mustHave<DataSource.HasAddOperation>()
.run { add(command) }
a

Antanas A.

04/15/2019, 2:45 PM
thank you all for answers
Kotlin could implement "infer" keyword like in TypeScript, and this could be written as: suspend fun <T, infer U> DataSource.mustHave(block: suspend T.() -> U): U
@Pavlo Liapota thanks for a solution, haven't thought about this
👍 1