是否有可能根据父函数参数推断高阶函数接收器类型?

时间:2018-05-15 19:01:00

标签: generics functional-programming kotlin type-conversion type-inference

给定一个功能:

inline fun <T: Any> executeSomething(
    defaultValue: String,
    entity: T,
    maybeDefault: String = defaultValue,
    onSuccess: (T) -> Unit
)

我想推断onSuccess,接收器类型T基于父函数参数或类似的东西。

这一个工作,编译器推断高阶函数onSucess中的实体接收器参数为String:

val someEntity: String = "some text"
executeSomething("action", someEntity)
{entity -> print (entity)} //prints: "some text" - entity: String

尽管如此,我试图让高阶函数动态定义它们的类型,有条件地基于maybeDefault参数值,通过这种方式强制执行静态定义类型。

该功能应该如下定义:

fun <T: Any,V: Any> executeSomething(
    defaultValue: String,
    entity: T,
    maybeDefault: String = defaultValue,
    newReceiver: V = if (defaultValue == maybeDefault) newReceiver as T else newReceiver as Int,
    onSuccess: (V) -> Unit
)

然后编译器应该成功,推断出staticDefineType类型:

val someNotDefault: String = "not default"
val someEntity: String = "some text"
executeSomething("default", someEntity, someNotDefault)
{newInferred -> print (newInferred)} //prints: 1 - newInferred: Int 

可能在Kotlin,我有哪些替代品?

0 个答案:

没有答案