我正在试验Kotlin中的反射功能,但我似乎不知道如何获得KType值.

Suppose I have a class that maps phrases to object factories. In case of ambiguity, the user can supply a type parameter that narrows the search to only factories that return that type of object (or some sub-type).

fun mapToFactory(phrase: Phrase,
          type: KType = Any::class): Any {...}

type needs to accept just about anything, including Int, which from my experience seems to be treated somewhat specially. By default, it should be something like Any, which means "do not exclude any factories".

如何将默认值(或任何值)指定给type

推荐答案

From your description, sounds like your function should take a KClass parameter, not a KType, and check the incoming objects with isSubclass, not isSubtype.

类型(kotlin-reflect中用KType表示)通常来自代码中声明的签名;它们表示函数作为参数或返回的一组广泛的值.类型由类、该类的泛型参数和可空性组成.JVM上运行时类型的问题是,由于擦除,无法确定泛型类变量的确切类型.例如,如果您有一个列表,则无法在运行时确定该列表的通用类型,即无法区分List<String>List<Throwable>.

不过,要回答您最初的问题,您可以在KClasscreateType()中创建KType:

val type: KType = Any::class.createType()

请注意,如果类是泛型的,则需要传递泛型参数的类型投影.在简单的情况下(所有类型变量都可以替换为星体投影),starProjectedType也可以工作.有关createTypestarProjectedTypesee this answer的更多信息.

Kotlin相关问答推荐

如何在 Big Data 中使用Inc过滤器?

使用数据存储首选项Kotlin Jetpack Compose

Kotlin中一个接口的实现问题

如何进行基于lambda/谓词的两个列表的交集?

KTOR';S函数`staticResources`在Kotlin本机目标上不可用

在构造函数中创建内部类实例时,只能使用包含类的接收器调用内部类的构造函数

在 Kotlin 中将两个字节转换为 UIn16

使用启动或使用 coroutineScope 启动协程之间的区别

Kotlin 插件之间的区别

Kotlin 条件格式字符串

正则表达式 FindAll 不打印结果 Kotlin

`this@classname` 在 Kotlin 中是什么意思?

调用单元测试验证伴随对象方法

如何在主线程上使用 Kotlin 协程 await()

launch 仅从 Kotlin 1.3 开始可用,不能在 Kotlin 1.2 中使用

Android 上的 Kotlin:将map到list

Kotlin 中更好的回调方法是什么?侦听器与高阶函数

Kotlin数据类打包

Recyclerview: listen to padding click events

Android Compose 生产准备好了吗?