代码之家  ›  专栏  ›  技术社区  ›  Alexey Romanov

仅推断Kotlin中的某些类型参数

  •  9
  • Alexey Romanov  · 技术社区  · 8 年前

    fun <A, B> foo(x: Any, y: A.() -> B) = (x as A).y()
    
    // at call site
    foo<String, Int>("1", { toInt() })
    

    B Int A String B 可以推断。

    有没有办法只提供 在调用站点并推断 B

    class <A> Foo() {
        fun <B> apply(x: Any, y: A.() -> B) = ...
    }
    
    // at call site
    Foo<String>().apply("1", { toInt() })
    

    我感兴趣的是科特林是否有更直接的解决方案。

    1 回复  |  直到 8 年前
        1
  •  7
  •   nhaarman    8 年前

    基于 this issue/proposal ,我会说不(还没有):

    手动:部分类型参数列表和默认类型参数:),其中 本质上允许做以下事情:

        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
        }