如果发生异常,分配什么a
或分配什么?b
Wrap a
and b
in aTry
处理异常情况。您还可以对这些进行模式匹配以提取值。
scala> class MyClass(val a: Try[String], val b: Try[String])
defined class MyClass
scala> new MyClass(Try("foo"(0).toString), Try("foo"(3).toString))
res0: MyClass = MyClass@6bcc9c57
scala> res0.a
res1: scala.util.Try[String] = Success(f)
scala> res0.b
res2: scala.util.Try[String] = Failure(java.lang.StringIndexOutOfBoundsException: String index out of range: 3)
scala> res0.a.get
res3: String = f
scala> res0.b.get
java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:658)
...
编辑评论。a
对和使用默认参数b
。
null
很糟糕,但这就是你所要求的。见选项
class MyClass(val a: Try[String] = null, val b: Try[String] = null)
scala> new MyClass(Success("a"))
res50: MyClass = MyClass@625aaaca
scala> res50.a
res51: scala.util.Try[String] = Success(a)
scala> res50.b
res52: scala.util.Try[String] = null
scala> new MyClass(b = Success("b"))
res53: MyClass = MyClass@68157e85
scala> res53.a
res54: scala.util.Try[String] = null
scala> res53.b
res55: scala.util.Try[String] = Success(b)