此Java代码的Scala等价物是什么,其中someMethodThatMightThrowException
在其他地方定义?
class MyClass {
String a;
String b;
MyClass() {
try {
this.a = someMethodThatMightThrowException();
this.b = someMethodThatMightThrowException();
} finally {
System.out.println("Done");
}
}
}
答案 0 :(得分:5)
class MyClass {
private val (a, b) =
try {
(someMethodThatMightThrowException(),
someMethodThatMightThrowException())
} finally {
println("Done")
}
}
try
是Scala中的表达式,因此您可以使用它的值。使用元组和模式匹配,您可以使用statement来获取多个值。
或者你可以使用几乎与Java相同的代码:
class MyClass {
private var a: String = _
private var b: String = _
try {
a = someMethodThatMightThrowException()
b = someMethodThatMightThrowException()
} finally {
println("Done")
}
}
答案 1 :(得分:1)
与伴侣对象
case class MyClass(a: String, b: String)
object MyClass {
def apply() = try {
new MyClass(
a = someMethodThatMightThrowException(),
b = someMethodThatMightThrowException()
)
} finally {
println("Done")
}
}
构造函数重载有点困难,因为我们无法包装这个(...):
def tryIt[T](something: => T) = try{
something
} finally {
println("Done")
}
case class MyClass(a: String, b: String) {
def this() = this(
tryIt(someMethodThatMightThrowException),
tryIt(someMethodThatMightThrowException)
)
}
答案 2 :(得分:1)
如果发生异常,分配的a
或b
是什么?在a
中换行b
和Try
来处理异常情况。您还可以对这些进行模式匹配以提取值。
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
很糟糕,但这就是你要求的。见Option
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)
答案 3 :(得分:1)
接近的事情如何:
scala> def foo = ???
foo: Nothing
scala> :pa
// Entering paste mode (ctrl-D to finish)
case class Foo(a: String = Foo.afoo, b: String = Foo.bfoo)
object Foo {
import util._
def afoo = Try (foo) recover { case _ => "a" } get
def bfoo = Try (foo) recover { case _ => "b" } get
}
// Exiting paste mode, now interpreting.
warning: there were 2 feature warning(s); re-run with -feature for details
defined class Foo
defined object Foo
scala> Foo()
res0: Foo = Foo(a,b)