I am creating a TypeToken-like system similar to what Gson has and I have stumbled upon something I do not understand.

这段代码的目的是只有一个TypeReference类,具有一个可以容纳多个泛型参数的泛型参数.将使用inline函数创建类,这样用户就不需要知道Holder类.

请考虑以下代码:

package testing

import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

abstract class TypeReference<T : Holder> {
    val type: Type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]

    override fun toString(): String {
        return type.typeName
    }
}

inline fun <reified T : Holder> create() = object : TypeReference<T>() {}

inline fun <reified WHAT> createSingle() = object : TypeReference<Single<WHAT>>() {}

class Foo

interface Holder

interface Single<T> : Holder

fun main(args: Array<String>) {
    println(create<Single<HashMap<Int, String>>>())
    println(create<Single<Foo>>())

    println(createSingle<HashMap<Int, String>>())
    println(createSingle<Foo>())
}

This is the output:

testing.Single<java.util.HashMap<java.lang.Integer, java.lang.String>>
testing.Single<testing.Foo>
testing.Single<WHAT>
testing.Single<WHAT>

It looks like to me as if the Single<WHAT> (sry for that generic name) does not get 'truly' inlined and some intermediate name gets generated.

I have also looked in the docs but I did not find examples regarding this.

How can I create what I initially intended to do? Why does this happen?

编辑.:

我想制造一个问题,但他们已经知道了.

一个非常相似的问题是发行here,据说是this的复制品.您也可以在后面的链接中投票.

供将来参考:此处使用Kotlin 1.2.50.

推荐答案

I decompile this code,found some different between two func

private static final TypeReference create() {
  Intrinsics.needClassReification();                 <---- here
  return (TypeReference)(new TypeReference() {
  });
}

private static final TypeReference createSingle() {
  return (TypeReference)(new TypeReference() {
  });
}

And manual add this code, work fine. Don't known too much about this, no document found.

inline fun <reified WHAT > createSingle() = Intrinsics.needClassReification().let {
    object : TypeReference<Single<WHAT>>() {}
}

result:

Single<java.util.HashMap<java.lang.Integer, java.lang.String>>

Single<Foo>

Single<java.util.HashMap<java.lang.Integer, java.lang.String>>

Single<Foo>

Kotlin相关问答推荐

如何在Jetpack Compose中从领域查询中读取数据?

在Jetpack Compose中创建波浪式文本动画:顺序中断问题

为什么 trySend 会发出假数据?

判断 Kotlin 变量是否为函数

Kotlin 中的密封和内部有什么区别?

如何为 Kotlin 中的每个循环设置以避免越界异常

Kotlin:伴随对象内的函数扩展

使用 LazyListScope 嵌套可组合项

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

Android 导航组件 - 向上导航打开相同的片段

零安全的好处

将 Android Studio 升级到 3.1.0 后的 Android Support 插件错误

如果我可以将 Flow 和 StateFlow 与生命周期范围 \ viewLifecycleOwner.lifecycleScope 一起使用,那么在 ViewModel 中使用 LiveData 有什么意义

main函数和常规函数有什么区别?

API 26 上未显示 Android 通知

用于代码生成的ANTLR工具版本4.7.1与当前运行时版本4.5.3不匹配

Kotlin out-projected 类型禁止使用

Kotlin Android:属性委托必须有一个 'getValue(DashViewModel, KProperty*>)' 方法

内联 onFocusChange kotlin

任务':app:kaptDebugKotlin'的Kotlin执行失败