简体   繁体   English

Scala:尝试和成功和失败

[英]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 我对它是如何工作有点困惑,我假设它是从我从Scala文档中的类似示例复制它

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 我知道onComplete需要一个以Try作为输入的函数,而Success和Failure是从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 . 传递给onComplete的参数是一个部分函数 Here is how you can define a partial function in the REPL: 以下是如何在REPL中定义部分函数:

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

Notice that the match keyword doesn't appear here. 请注意, match关键字不会出现在此处。

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. PartialFunction[Int, String](Int => String)的子类,如果您尝试在未定义的值上调用它,则会引发MatchError异常。

Whenever the compiler expects a parameter of type Int=>String a PartialFunction[Int, String] can be passed (since it's a subclass). 每当编译器期望Int=>String类型的参数时,就可以传递PartialFunction[Int, String] (因为它是一个子类)。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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