Try expression of Unit does not conform to expected type

时间:2017-07-31 12:01:34

标签: java scala

I have a scenario where I need to call a Java API from a Scala code which returns void and throws an exception in case lets say if the argument is not valid. I am currently handling it as follows, however I was wondering if there is a way to avoid var and if there is an idiomatic way to achieve this in Scala:

object TestTry extends App {

  def createSampleRequest(message: String): Option[SampleRequest] = {
    val sampleRequest = new SampleRequest()

    //I really want to avoid var
    var parsedSampleRequest = Option(SampleRequest)

    //Calling a Java method returns void
    try sampleRequest.fromString(fix, null, true) 
    catch {
      case e: InvalidMessage => parsedSampleRequest = Option.empty
    }

    parsedSampleRequest
  }

}

2 个答案:

答案 0 :(得分:2)

一种方法是使用Try

export abstract class IRemoteServiceConfig { ... }

如果对import scala.util.Try def createSampleRequest(message: String): Option[SampleRequest] = { val sampleRequest = new SampleRequest() Try(sampleRequest.fromString(fix, null, true)) .map(s => Option(sampleRequest)) .getOrElse(None) } 的调用引发异常,则fromString将为result;如果调用没有抛出异常,None将是包含result实例的Some[SampleRequest]

正如@OlegPyzhcov在评论中指出的那样,更简洁的版本是:

sampleResult

答案 1 :(得分:1)

您可以完全消除变量并在需要的地方返回:

object TestTry extends App {

  def createSampleRequest(message: String): Option[SampleRequest] = {
    val sampleRequest = new SampleRequest()

    try 
      sampleRequest.fromString(fix, null, true)
      Some(sampleRequest)
    catch
      case e: InvalidMessage => None
  }
}