feature

Option type, Some and None

The Option type is a very convenient way to avoid checking null pointers.
Here is a classical "null pointer checking" situation:
def getString : String = {
  ...
  "a string"
  ...
  null
}
 
val str = getString
val str2 = if (str == null) "[null]" else str
This code can be replaced by the following one:
def getString : Option[String] = {
  ...
  Some("a string")
  ...
  None
}
 
val str = getString.getOrElse("[null]")
It's using the Option type together with the Some case class and the None object (from Option.scala):
sealed abstract class Option[+A] extends Product {
  ...
}

final case class Some[+A](x: A) extends Option[A] {
  ...
}
 
case object None extends Option[Nothing] {
   ...
}

Tuple patterns

In this post I'd like to present a basic but useful feature:
When you need to quickly create a method that returns a set of data instead of only one instance of an existing class, you can use tuples (and the corresponding pattern matching).
Imagine that you need to define a method that takes 2 Ints as parameters and returns 2 Ints, without creating an additional class with 2 attributes. You can return a Tuple as done in the following example:

// returns the sum and product of 2 Ints
def sumAndProduct(n:Int, m:Int) = (n+m, n*m)

Thanks to Tuple patterns, invoking this method and getting the sum and product as returned by the function is straightforward:
val (sum, product) = sumAndProduct(5,6)
println(sum) // prints "11"
println(product) // prints "30"
The tuple values can also be accessed this way:
val ret = sumAndProduct(5,6)
println(ret._1) // prints "11"
println(ret._2) // prints "30"
Can't be easier :))
Syndicate content