在 Kotlin 中推断部分类型参数

9

我有一个带有两个类型参数的方法,只能从实参中推断出其中一个参数的类型,类似于以下代码(无需评论此处的强制类型转换是有害的,这段代码仅为示例):

fun <A, B> foo(x: Any, y: A.() -> B) = (x as A).y()

// at call site
foo<String, Int>("1", { toInt() })

然而,如果知道AString,编译器可以判断BInt。更一般地说,如果知道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 是否有更直接的解决方案。


如果您同时提供调用站点(具有显式类型规范的工作站点和您所针对的站点),将有助于更好地理解。 - guenhter
@guenhter 已添加。 - Alexey Romanov
1个回答

7

根据这个问题/建议,我认为还没有(实现):

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
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接