我有一个带有两个类型参数的方法,其中只有一个可以从参数中推断出来,类似于(无需评论这种强制转换是邪恶的,主体纯粹是为了示例)
fun <A, B> foo(x: Any, y: A.() -> B) = (x as A).y()
// at call site
foo<String, Int>("1", { toInt() })
但是,编译器可以告诉 B
是 Int
if 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() })
我对 Kotlin 是否有更直接的解决方案很感兴趣。
最佳答案
基于 this issue/proposal ,我会说不(还没有):
Hello, I am proposing two new feature for kotlin which go hand in hand: partial type parameter list and default type parameters :) Which in essence allows to do something as the following:
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>() }
It would be even nicer, if we can define something like:
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("...") }
And then don't even have to write
_
fun foo() { val i: Any = 1 Test(i).narrow<Int>() //default type parameter, let Kotlin infer the first type parameter }
关于kotlin - 在 Kotlin 中仅推断某些类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46401921/