首页 > 解决方案 > KeyNotFoundException 与在 Kotlin 中返回 null

问题描述

我正在尝试决定 Kotlin 接口中的一个函数,该函数根据给定键从配置中读取值。这两个选项是

/**
 * Reads a configuration value for the specified key.
 * @param key The key to the configuration value to retrieve
 * @return The configuration value if the key is present, exception otherwise
 */
fun readValue(key: String): String
/**
 * Reads a configuration value for the specified key.
 * @param key The key to the configuration value to retrieve
 * @return The configuration value if the key is present, null otherwise
 */
fun readValue(key: String): String?

如图所示,主要区别在于引发异常或返回空值。

鉴于我在 Java 和 C# 方面的背景,我觉得编写第二种形式并要求调用者在访问值之前检查 null 是很自然的,但是我不确定这是否适用于 Kotlin,或者一般偏好避免返回 null尽可能的值。

标签: design-patternskotlinnull

解决方案


在 Kotlin 中,您可以进行不错的 null 处理。所以反对java,不用避免null,可以拥抱它。

所以我会选择你的第二个选项,让你的 Api 的消费者自己决定。

他们可以使用 Elvis Operator:

val value = readValue("key") ?: "";
val value2 = readValue("key2") ?: throw IllegalArgumentException();

或者添加他们想要使用的确切扩展方法。

fun Repository.readOrEmpty(key:String):String {
    return this.readValue(key)?:""
}
fun Repository.readOrElse(key:String, defaultValue:String):String {
    return this.readValue(key)?:defaultValue
}
fun Repository.readOrThrow(key:String):String {
    return this.readValue(key)?:throw IllegalArgumentException();
}

如果您选择第一个选项,这两种用法都会很尴尬/不可能。


推荐阅读