dimanche 11 août 2019

KeyNotFoundException vs returning null in Kotlin

I'm trying to decide on a function in a Kotlin interface that reads a value from configuration based on a give key. The two options would be

/**
 * 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?

Where, as show, the main difference is raising an exception or returning null value.

Given my background in Java and C# it feel natural to me to write the second form and require the caller to check for null before accesing the value, however I'm not sure whether that applies to Kotlin or there's a general preference to avoid returning null values whenever possible.

Aucun commentaire:

Enregistrer un commentaire