I am just a beginner in scala and I am learning about the functions. I just developed a small piece of code as below.
class OptionClass {
}
object OptionClass {
def main(args: Array[String]) {
println("This is my third code")
def add(a: Int, c: Int, d: Option[Int]): Int = {
d match {
case Some(d) =>
val f = a + c + d
f
case None => a + c
}
}
val result = add(1, 2, None)
println(s"The result value is $result")
val newResult = add(1, 2, Some(5))
println(s"The new result is $newResult")
val revisedResult = add(1, 2)
println(s"The result value is $revisedResult")
//****Adding the code snippets as per the comments below as it may be useful for someone else who refers the questio
def addVal(a:Int,b:Option[Int]= None):Int = {
a+b.getOrElse(10)
}
val firstResult=addVal(1)
println(s"The firstResult is $firstResult")
val secondResult=addVal(1,Some(2))
println(s"The secondResult is $secondResult")
val thirdResult=addVal(1,None)
println(s"The thirdResult is $thirdResult")
}
}
My question is here is,
When I called the function using add(1,2,None)) and add(1,2,Some(5)) the code works, I tried calling the function using add(1,2) and code has issues. Even though I have mentioned the third argument is option, why should we mention the third argument as None or Some(d) (is some(d) is the right way to pass it?). It would be very helpful if you suggest the correct way to use the Option according to this code.