简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM