Hi, Is it possible to have function which has two ...
# announcements
a
Hi, Is it possible to have function which has two generic types and explicitly define only one type in call sites:
Copy code
`
        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
I don’t think you can have partial content in
<>
c
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
I would recommend:
Copy code
fun <T> DataSource.mustHave(): T =
    (this as? T) ?: throw RuntimeException("Operation is not supported")
And then you can write
Copy code
dataSource
.mustHave<DataSource.HasAddOperation>()
.add(command)
or following, if you want to call several methods:
Copy code
dataSource
.mustHave<DataSource.HasAddOperation>()
.run { add(command) }
a
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