Java与Kotlin方法冲突如何处理?以JsonObject的getValue方法为例
解决JsonObject调用Map的getValue方法冲突的方案
1. 编写自定义扩展函数
给JsonObject封装一个扩展函数,把强转逻辑藏在内部,后续调用就简洁直观:
import jakarta.json.JsonObject import jakarta.json.JsonValue // 专门调用Map版本的getValue fun JsonObject.getMapValue(key: String): JsonValue = (this as Map<String, JsonValue>).getValue(key)
使用时直接调用扩展函数即可:
val targetValue = jsonObject.getMapValue("yourKey")
2. 用Map操作符替代
JsonObject支持Map的[]操作符,它不会和JsonValue的getValue方法冲突。如果需要和Map的getValue一致的非空行为(找不到Key时抛出异常),可以用!!快速实现:
val targetValue = jsonObject["yourKey"]!!
要是想抛出和Map的getValue完全一致的NoSuchElementException,可以写得更严谨:
val targetValue = jsonObject["yourKey"] ?: throw NoSuchElementException("Key 'yourKey' is missing from JsonObject")
3. 用函数引用明确指定调用目标
通过Map的函数引用,直接指定调用Map版本的getValue,避免编译器自动匹配JsonValue的方法:
val targetValue = Map<String, JsonValue>::getValue(jsonObject, "yourKey")
4. 借助with块批量处理
如果一段代码里需要多次调用Map的方法,可以用with块一次性完成强转,块内直接调用Map的方法即可:
with(jsonObject as Map<String, JsonValue>) { val value1 = getValue("key1") val value2 = getValue("key2") // 其他Map相关操作 }
内容的提问来源于stack exchange,提问作者Todd O'Bryan
相关产品推荐
相关产品推荐

