0

A simple function literal can be written as

def add(x : Int) = x + 2

In the above example I understand add is a function that takes an Int and gives an Int. Its type is add: (x: Int)Int

It is very clear.

But the below example which is of type Option[Int] => Int it is a bit unclear

scala>  def matchFunction : Option[Int] => Int = {
     |   case Some(x) => x
     |   case None => 0
     | }
matchFunction: Option[Int] => Int

In the second example, can anyone explain why the type should it not be

def matchFunction (x : Option[Int]) : Int

Also please explain what is the difference between the above function and the one below that uses match from a type perspective

def matchFunction (x : Option[Int]) : Int = x match {
  case Some(x) => x
  case None => 0
}
Srinivas
  • 2,010
  • 7
  • 26
  • 51
  • `add` is a method not function. so you want to know https://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala – chengpohi Nov 18 '17 at 12:37
  • @chengpohi, why is add a method, but matchFunction a function. Both are def, so why is one different to the other? – Srinivas Nov 19 '17 at 11:12
  • `matchFunction` is a parameterless method, so you can use it like a variable, and it's returning a `function`. equal: `def matchFunction(): ...` – chengpohi Nov 19 '17 at 12:44

1 Answers1

1

Basically this is one of functional programming aspects: higher-order functions - those who takes other functions as parameters, or whose result is a function. Option[Int] => Int is an anonymous function which takes Option[Int] as a parameter and returns Int, anonymous function can always be expressed using def, def matchFunction(x : Option[Int]): Int = { ... } is just another variant to express Option[Int] => Int = { ... }. Higher-order functions are useful for generalization, polymorphism. So you may pass your matchFunction to function which takes Option[Int] => Int function as a parameter. List(Some(1), None, Some(2)).map(matchFunction) will give you List(1, 0, 2).

https://www.scala-exercises.org/scala_tutorial/higher_order_functions

janis.kom
  • 38
  • 8