仅在Kotlin中推断一些类型参数

Ale*_*nov 6 kotlin

我有一个带有两个类型参数的方法,其中只有一个可以从参数中推断出来,类似于(不需要评论这个演员是邪恶的,身体纯粹是为了举例)

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)

然而,编译器可以告诉BInt ,如果 AString.更一般地说,如果它知道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是否有更直接的解决方案感兴趣.

nha*_*man 7

基于这个问题/提案,我会说不(还没有):

您好,我为 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>()
    } 
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
    }
Run Code Online (Sandbox Code Playgroud)