How to declare, set, and use Option, Some, and None fields in Scala

I don’t have much time for a discussion today, but if you’re looking for an example of how to declare, set, and use Option fields in Scala, I hope this source code is helpful:

case class Address (city: String, state: String, zip: String)

class User(email: String, password: String) {
    var firstName = None: Option[String]
    var lastName = None: Option[String]
    var address = None: Option[Address]
}

object Test extends App {

    // populate the object
    val u = new User("al@example.com", "secret")
    u.firstName = Some("Al")
    u.lastName = Some("Alexander")
    u.address = Some(Address("Talkeetna", "AK", "99676"))

    // print the object information
    println(s"First Name: ${u.firstName.getOrElse("not assigned")}")
    println(s"Last Name:  ${u.lastName.getOrElse("not assigned")}")
    u.address.foreach { a =>
        println(a.city)
        println(a.state)
        println(a.zip)
    }

}

I’ll try to explain this when I have more time, but because it’s a complete working example, you can run it on your own computer and tweak it to see how it all works.