Does it make sense to return Try [Option [String]]?
I am writing a method that has three possible return states:
- Operation may fail with an exception
- The operation can be performed on a String result
- Operation can be performed without results
Is the return type displayed correctly Try[Option[String]]
? Or is there a better alternative?
+3
source to share
2 answers
Your approach is great. Another approach is to define your own case classes / objects
sealed trait Result
case class OperationFailed(e: Exception) extends Result
case class SuccessValue(str: String) extends Result
case object SuccessNoValue extends Result
Edit:
This approach may work better with pattern matching, especially if you are using Akka.
val f: Any => Any = { case x: Try[Option[String]] => x.get.get.toUpperCase }
f(Try(Some("x")))
f(Try(Some(5))) // Throws java.lang.ClassCastException
The above example will show the following warning
warning: non-variable argument The [String] option in the scala.util.Try template [Option [String]] is not set because it is being removed
+1
source to share
Lift Box does a good job of combining Option and Try semantics
A The box can be:
- Full (value) => Some (value): Option
- Empty => No: option
- Failure (ex) => Failure: try
http://scala-tools.org/mvnsites/liftweb-2.3/net/liftweb/common/Box.html
+2
source to share