Maik Klein
Maik Klein

Reputation: 16148

Scala - Case Sequence

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?

Upvotes: 2

Views: 212

Answers (3)

Jan
Jan

Reputation: 1777

test is a function of type "Int => Int" test1 is a method that uses a partial function (the match expression) internally. So they are not equal.

If you want to check Types use the REPL:

:type test
Int => Int

:type test1 _
Int => Int

Upvotes: 0

Brian Smith
Brian Smith

Reputation: 3381

The former code does return a function of type Int => Int.

Welcome to Scala version 2.9.1.final (Java HotSpot(TM) Client VM, Java 1.6.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

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

// Exiting paste mode, now interpreting.

test: Int => Int

scala> test
res0: Int => Int = <function1>

scala> test.apply(1)
res1: Int = 2

Perhaps what is confusing is that apply can be called directly:

scala> test(1)
res2: Int = 2

Upvotes: 5

Kim Stebel
Kim Stebel

Reputation: 42037

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.

Upvotes: 6

Related Questions