Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 类型推断仅适用于扩展函数_Kotlin - Fatal编程技术网

Kotlin 类型推断仅适用于扩展函数

Kotlin 类型推断仅适用于扩展函数,kotlin,Kotlin,下面的代码工作正常,对foo.get()扩展函数的调用返回正确的类型BarImpl open class Bar class BarImpl: Bar() class Foo<T : Bar> inline fun <reified T : Bar> Foo<T>.get(): T { return SomeMap(this).get(T::class) } class Activity { lateinit var foo: Foo&

下面的代码工作正常,对
foo.get()
扩展函数的调用返回正确的类型BarImpl

open class Bar
class BarImpl: Bar()

class Foo<T : Bar> 

inline fun <reified T : Bar> Foo<T>.get(): T {
    return SomeMap(this).get(T::class)
}

class Activity {
    lateinit var foo: Foo<BarImpl>
    val barImpl = foo.get()
}

如何将函数移动到类中?

扩展函数返回
Foo
类型参数的结果。因此,可以从接收方类型推断结果类型

成员函数结果类型与
Foo
type参数没有任何共同之处,除了名称,这对编译器来说没有任何意义。通过编写和编译以下代码,您可以看到方法中的
T
和类中的
T
是不同的类型:

Foo<BarImpl>().get<BarImpl2>()

扩展函数返回
Foo
type参数的结果。因此,可以从接收方类型推断结果类型

成员函数结果类型与
Foo
type参数没有任何共同之处,除了名称,这对编译器来说没有任何意义。通过编写和编译以下代码,您可以看到方法中的
T
和类中的
T
是不同的类型:

Foo<BarImpl>().get<BarImpl2>()
Foo<BarImpl>().get<BarImpl2>()
class Foo<T : Bar>(private val clazz: KClass<T>) {
    fun get(): T {
        return SomeMap(this).get(clazz)
    }

    companion object {
        inline operator fun <reified T : Bar> invoke() = Foo(T::class)
    }
}