在 Kotlin 中一般将一种类型的值转换为另一种类型的值

问题描述 投票:0回答:1

我有一个包含 KType 对到 String 中的值的映射,我希望将这些值转换为其对中 KType 的类型(例如,将“123”转换为值为 123 的 Int)。

知道该值始终可以转换为成对的 KType,因为地图是以这种方式构建的,我如何才能用“通用”术语来实现这一点?意思是,不要为每种可以想象到的类型创建 switch 语句或类似语句。这可能吗?

// Do something to the values of each pair that converts them to the type in their pairing
val map = mapOf(kotlin.Boolean to "true", kotlin.Int to "123", kotlin.String to "hello")

 // "true" would become true
 // "123" would become 123
 // "hello" would stay as a String with the value "hello"

抱歉,如果我的解释不是很清楚。

kotlin types reflection maps
1个回答
0
投票

没有通用的方法可以做到这一点。例如,有很多方法可以在整数和字符串之间进行转换——例如十六进制。

意思是,不要为每种可以想象到的类型创建 switch 语句或类似的语句。

你必须这样做。

© www.soinside.com 2019 - 2024. All rights reserved.