kotlin - 在 Kotlin 中仅推断某些类型参数

标签 kotlin

我有一个带有两个类型参数的方法,其中只有一个可以从参数中推断出来,类似于(无需评论这种强制转换是邪恶的,主体纯粹是为了示例)

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

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

但是,编译器可以告诉 BInt if 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() })

我对 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/

相关文章:

arrays - 如何用Kotlin检查2D数组中是否存在值?

generics - 接口(interface)中的通用函数返回具体实现

java - 我如何在 Kotlin 中编写 Java 括号 "[ ]"?

android - android/kotlin 网格布局中单元格的高度和宽度相同

java - 如何修复 Kotlin 编译器错误推断类型为 () -> Unit but Consumer<Throwable?>?预计

kotlin - 中缀表示法和 with(...) 不能按我的预期工作

enums - Kotlin:如何使用扩展函数扩展枚举类

android - 使用底部导航 View (如Youtube)处理堆栈

java - 如何在 Java/Android 中查找内存泄漏

android - Kotlin:使用 Gradle 进行增量编译