Casey Howard
Casey Howard

Reputation: 1

What is the best way to handle nullable vals in Koltin?

I have a function that accepts nullable Strings, but requires them to be non-null.

fun fn(a: String?) {
    if (a == null) {
        logger.warn("a is null, aborting")
        return
    }
    // do something
    fnThatDoesNotAcceptNulls(a)
}

Is there a better way to check if the value is null and return from the function in Kotlin?

Upvotes: 0

Views: 72

Answers (1)

Boken
Boken

Reputation: 5447

You can resolve this problem by:

  1. using just if (your version)
fun fn(a: String?) {
    if (a == null) {
        logger.warn("a is null, aborting")
        return
    }
    // do something
    fnThatDoesNotAcceptNulls(a)
}
  1. using just if
fun fn(a: String?) {
    if (a != null) {
        // do something
        fnThatDoesNotAcceptNulls(a)
        return
    }

    logger.warn("a is null, aborting")
}
  1. using if (but without logging):
fun fn(a: String?) {
    if (a != null) {
        // do something
        fnThatDoesNotAcceptNulls(a)
    }
}
  1. using if-else
fun fn(a: String?) {
    if (a == null) {
        logger.warn("a is null, aborting")
    } else {
        // do something
        fnThatDoesNotAcceptNulls(a)
    }
}
  1. using when (with expression body - depends on return type!):
fun fn(a: String?) = when (a) {
    null -> {
        logger.warn("a is null, aborting")
    }
    else -> {
        // do something
        fnThatDoesNotAcceptNulls(a)
    }
}
  1. using "elvis" (?:)
fun fn(a: String?) {
    val value = a ?: return
    
    // do something
    fnThatDoesNotAcceptNulls(value)
}
  1. using let extension:
fun fn(a: String?) {
    a?.let {
        // do something
        fnThatDoesNotAcceptNulls(it)
    }
}
  1. using let extension (with handling "negative" case when a is null):
fun fn(a: String?) {
    a?.let {
        fnThatDoesNotAcceptNulls(a)
    } ?: logger.warn("a is null, aborting")
}
  1. using run extension:
fun fn(a: String?) {
    a?.run {
        // do something
        fnThatDoesNotAcceptNulls(this)
    }
}
  1. using run extension (with handling "negative" case when a is null):
fun fn(a: String?) {
    a?.run {
        // do something
        fnThatDoesNotAcceptNulls(this)
    } ?: logger.warn("a is null, aborting")
}

In private, I like option 5 (with elvis) and those with extensions. But it all depends on the situation or the case.

Upvotes: 3

Related Questions