在Kotlin中只推荐一些类型参数
我有一个有两个类型参数的方法,其中只有一个可以从参数中推导出来,比如(不需要评论这个演员是邪恶的,身体纯粹是为了举例)
fun <A, B> foo(x: Any, y: A.() -> B) = (x as A).y() // at call site foo<String, Int>("1", { toInt() })
但是, 如果 A
是String
,编译器可以告诉B
是Int
。 更一般地说,如果知道A
,则可以推断出B
有没有办法只在呼叫地点提供A
并推断B
?
当然,标准的Scala方法的工作原理是:
class <A> Foo() { fun <B> apply(x: Any, y: A.() -> B) = ... } // at call site Foo<String>().apply("1", { toInt() })
我对Kotlin是否有更直接的解决方案感兴趣。
基于这个问题/建议 ,我会说不(t):
您好,我为kotlin提出了两个新功能:部分类型参数列表和默认类型参数:)本质上允许执行以下操作:
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>() }
如果我们能够定义如下的话,那将更好:
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("...") }
然后甚至不必写
_
fun foo() { val i: Any = 1 Test(i).narrow<Int>() //default type parameter, let Kotlin infer the first type parameter }