Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by

Kotlin has a '?' operator which can be used to handle nullable types:

fun f(nullable: String?) {
  val nullable_length = nullable?.length;
  val length_or_zero = nullable_length ?: 0;
  val prefixed_nullable = nullable?.let {
    "prefix_" + it
  }
}

Here, nullable_length is either an integer or null. length_or_zero is either the length of string or 0 if it was null. prefixed_nullable is either null or the original string with a prefix, depending on whether it was null.

What is the clojure equivalent of this feature for dealing with nils?

1 Answer

+2 votes
by
edited by

Probably some-> and some->>:

(some-> "foo" (.length)) ;;=> 3
(some-> nil (.length)) ;;=> nil
by
And those parens around `.length` and `.-length` are optional.
by
That's true, thanks for adding that
...