我有一个包含 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"
抱歉,如果我的解释不是很清楚。
没有通用的方法可以做到这一点。例如,有很多方法可以在整数和字符串之间进行转换——例如十六进制。
意思是,不要为每种可以想象到的类型创建 switch 语句或类似的语句。
你必须这样做。