Design patterns KeyNotFoundException vs在Kotlin中返回null

Design patterns KeyNotFoundException vs在Kotlin中返回null,design-patterns,kotlin,null,Design Patterns,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 r

我试图确定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
其中,如图所示,主要区别在于引发异常或返回空值


考虑到我在Java和C方面的背景,我觉得编写第二个表单并要求调用方在访问值之前检查null是很自然的,但是我不确定这是否适用于Kotlin,或者有一个普遍的偏好,即尽可能避免返回null值。

在Kotlin中,您有很好的null处理。与java相反,无需避免null,您可以接受它

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

他们可以使用Elvis操作符:

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();
}

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

在Kotlin中,您有不错的空处理。与java相反,无需避免null,您可以接受它

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

他们可以使用Elvis操作符:

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();
}

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

这个问题是基于观点的。即使在没有例外的语言中,一些函数是否应该返回null或panic仍然存在争议。是的,它有点基于观点,但是(在我看来)第二种观点(exception/panic)的基础在kotlin已经缩小了。我想为第一个选项(例外)提供一些例子,这将提供一些好处,并考虑到kotlin的特殊语言特性。这个问题是基于观点的。即使在没有例外的语言中,一些函数是否应该返回null或panic仍然存在争议。是的,它有点基于观点,但是(在我看来)第二种观点(exception/panic)的基础在kotlin已经缩小了。我想为第一个选项(例外)提供一些示例,这些示例将提供一些好处,并将kotlin的特殊语言功能考虑在内。或者,使用函数式返回选项,或者使用函数式返回选项