Library contents

Scala Option.getOrElse

Supply a printable phone label when an optional contact field has no value.

A simple example

Option.getOrElse

  1. Start with No string supplied
  2. Do this Try to read its length
  3. Result No length available
Checking for a missing value first lets the program choose a default before accessing a member.

Syntax

Scala syntax
phone.getOrElse(fallback)
Run these examples in Scala

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

Print a label when the phone number is missing

A school prints contact cards from an enrollment form. Some families leave the optional phone field blank, so the printer needs a readable fallback before it measures or displays that field.

ResultAsk for a phone number
Lesson.scala
object Lesson {
    def main(args: Array[String]): Unit = {
        val phone: Option[String] = None
        println(phone.getOrElse("Ask for a phone number"))
    }
}
Output
Ask for a phone number

The missing contact follows the fallback branch, so the card still has a printable phone field.

Advertisements

Print an existing extension

A department saved its internal extension in the staff directory. Confirm that a contact value is available before printing it on a dispatch slip.

GivenExtension 204
Worked resultContact available

Flag an unfilled contact field

A delivery booking reaches reception without a contact value. Confirm that a contact value is available before printing it on a dispatch slip.

GivenMissing value
Worked resultAsk for contact

What to watch for

Handle empty text separately if the form treats a blank entry differently from an absent value.

Documentation for Option.getOrElse