O'Reilly logo

Learning Scala Programming by Vikash Sharma

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Matching a constructor

Okay, what does a constructor pattern look like? It's about matching a constructor against a value, or we could say, extracting values of our choice. Let's take an example:

def safeToInt(canBeNumber: String): Option[Int] = { 
  try { 
    Some(canBeNumber.toInt) 
  } catch { 
    case NonFatal(e) => None 
  } 
} 
 
safeToInt("10") match { 
  case None => println("Got nothing") 
  case Some(value) =>  println(s"Got $value") 
} 

The result is as follows:

Got 10 

The only difference we can see here is, instead of providing a variable, we gave a constructor pattern. Some(value) lets you extract the value out of itself. Here in the given example, the safeToInt method returns an Option type. We're going to learn about types in subsequent sections. For ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required