jeudi 30 septembre 2021

Swift-like "guard-let" in Scala

In Swift, one can do something like:

    guard let x = z else {return}  // z is "String?"

In this simple case, if z (an optional) is empty, the function will exit.

I really like this structure and recently started developing in Scala, and I was wondering if there's an equivalent in Scala.

What I found is this:

    val x = if (z.isEmpty) return else z.get  // z is "Option[String]"

It works - but I still wonder if there's a more "Scala-ish" way of doing it.

Aucun commentaire:

Enregistrer un commentaire