0

I've implemented the following code to handle the completion of my future, and it compiles fine

resultFuture.onComplete({
      case Success => // success logic
      case Failure => // failure logic
    })

I'm a little confused as to how it works, I'm presuming it does as I copied it from a similar example from the Scala documentation

I understand that onComplete requires a function that takes a Try as input, and that Success and Failure are case classes that extend from Try

What I don't understand is how you can case on these without first performing a match of some type.

How is this possible here?

DJ180
  • 18,724
  • 21
  • 66
  • 117
  • possible duplicate of [How is a match word omitted in Scala?](http://stackoverflow.com/questions/7168026/how-is-a-match-word-omitted-in-scala) – senia Nov 24 '13 at 04:12
  • Before voting to close, please consider whether the OP would be at all likely to find the other post considered a duplicate. Two questions with the same answer are not necessarily the same question. – Ed Staub Nov 24 '13 at 04:41

1 Answers1

2

The argument being passed to onComplete is a partial function. Here is how you can define a partial function in the REPL:

val f: PartialFunction[Int, String] = {
  case 3 => "three"
  case 4 => "four"
}

Notice that the match keyword doesn't appear here.

PartialFunction[Int, String] is a subclass of (Int => String), if you try to call it on a value that it's not defined on, a MatchError exception would be raised.

Whenever the compiler expects a parameter of type Int=>String a PartialFunction[Int, String] can be passed (since it's a subclass). Here is a somewhat contrived example:

def twice(func: Int => String) = func(3) + func(3)

twice({
  case 3 => "three"
  case 4 => "four"
})

res4: java.lang.String = threethree

twice({ case 2 => "two" })

scala.MatchError: 3 (of class java.lang.Integer)
thesamet
  • 6,382
  • 2
  • 31
  • 42