一个模式如何匹配此方法的成功或失败:
trait FunctionApi:
def computeTry(funct: Try[String] => Unit): Unit = ??? // some ops
def actUponTry(functionApi: FunctionApi): String = {
// This below could be something other than match as
// long as `Success` or `Failure` is apparent)
functionApi.computeTry(...) match
// When Try is ... (get Try + exception or value)
// Success(value) => // Act on Success & value
s"Success with $value"
// Failure(ex) => // Act on Failure & ex
s"Failure with exception ${ex.getString}"
}
如果有另一种名为isFunctionApi
的方法,那么这个“匹配测试”是否可以更通用?computeTry2
computeTry2(funct: Try[Long] => Unit): Unit
不要使用外部库。
也许如何在 Scala 中模式匹配函数?有帮助吗?
也许有办法使用另一个包装特征或方法来提取成功/失败参数?
附加编辑:
最终目标是赋值一个 Promise 来执行 Future。(我想自己做这部分。)调用代码可能如下所示:
val success = Success("Some String")
val succeeding = new FunctionApi:
def computeTry(continuation: Try[String] => Unit): Unit =
continuation(success)
val wasSuccess = actUponTry(succeeding).computeTry()
编辑#2:我设法让它工作 - 随着问题的发展,我将关闭这个问题。
def actUponTry(functionApi: FunctionBasedApi): StringBasedApi = {
class StringBasedApiX extends StringBasedApi {
def computeTry(): String = {
functionApi.computeTry {
case Success(value) => s"Success with $value"
case Failure(ex) => s"Failure with exception ${ex.getMessage}"
}
}
}
new StringBasedApiX
}
/**
* Dummy example of a callback-based API
*/
trait FunctionBasedApi:
def computeTry(funct: Try[String] => String): String
/**
* API similar to [[CallbackBasedApi]], but based on `String` instead
*/
trait StringBasedApi:
def computeTry(): String
附测试代码:
test("test matching") {
val success = Success("Some String")
val stringBasedApi = new FunctionBasedApi:
def computeTry(funct: Try[String] => String): String = funct(success)
val wasSuccess = actUponTry(stringBasedApi).computeTry()
assertEquals(wasSuccess, s"Success with ${success.get}")
}
但我发现我尝试使用期货来做到这一点的方式与上面的代码不同(上面的...我无法进行模式匹配)。