我有一个带有两个类型参数的方法,其中只有一个可以从参数中推断出来,类似于(不需要评论这个演员是邪恶的,身体纯粹是为了举例)
fun <A, B> foo(x: Any, y: A.() -> B) = (x as A).y()
// at call site
foo<String, Int>("1", { toInt() })
Run Code Online (Sandbox Code Playgroud)
然而,编译器可以告诉B是Int ,如果 A是String.更一般地说,如果它知道A,B可以推断出来.
有没有办法只A在呼叫站点提供并推断B?
当然,标准的Scala方法有效:
class <A> Foo() {
fun <B> apply(x: Any, y: A.() -> B) = ...
}
// at call site
Foo<String>().apply("1", { toInt() })
Run Code Online (Sandbox Code Playgroud)
我对Kotlin是否有更直接的解决方案感兴趣.
基于这个问题/提案,我会说不(还没有):
您好,我为 kotlin 提出了两个相辅相成的新功能:部分类型参数列表和默认类型参数 :) 本质上允许执行以下操作:
Run Code Online (Sandbox Code Playgroud)data class Test<out T>(val value: T) inline fun <T: Any, reified TSub: T> Test<T>.narrow(): Test<TSub>{ return if(value is TSub) Test(value as TSub) else throw ClassCastException("...") } fun foo() { val i: Any = 1 Test(i).narrow<_, Int>() // the _ means let Kotlin infer the first type parameter // Today I need to repeat the obvious: Test(i).narrow<Any, Int>() }如果我们可以定义如下内容,那就更好了:
Run Code Online (Sandbox Code Playgroud)inline fun <default T: Any, reified TSub: T> Test<T>.narrow(): Test<TSub>{ return if(value is TSub) Test(value as TSub) else throw ClassCastException("...") }然后甚至不必写
_Run Code Online (Sandbox Code Playgroud)fun foo() { val i: Any = 1 Test(i).narrow<Int>() //default type parameter, let Kotlin infer the first type parameter }
| 归档时间: |
|
| 查看次数: |
520 次 |
| 最近记录: |