Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Case Sequence

Tags:

scala

I just read about case sequence as partial functions and the syntax is a little bit strange.

For example

def test: Int => Int = {
  case 1 => 2
  case 2 => 3
  case _ => 0
}    

I would expect that test has no arguments and would return a function of type Int => Int

But after some testing it seems that it takes an int as an argument and returns an int, so I rewrote it to...

def test1(i: Int): Int =
  i match {
    case 1 => 2
    case 2 => 3
    case _ => 0
  }

Are test and test1 equal?

like image 455
Maik Klein Avatar asked Jul 20 '26 08:07

Maik Klein


1 Answers

They are not equal. test is a method that returns a Function1[Int,Int] and test1 is a method that takes an Int and returns an Int. This is also completely unrelated to the pattern matching expression.

like image 137
Kim Stebel Avatar answered Jul 22 '26 00:07

Kim Stebel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!