DJ180
DJ180

Reputation: 19854

Scala: Try and casing on Success and Failure

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?

Upvotes: 0

Views: 1459

Answers (1)

thesamet
thesamet

Reputation: 6582

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)

Upvotes: 2

Related Questions