L'aggiunta di registrazione se il valore di ritorno è None
-
26-10-2019 - |
Domanda
Supponiamo che ci sono due funzioni findUser(id:String):Option[User]
e findAddress(user:User):Option[Address]
invocati come segue:
for(user <- findUser(id); address <- findAddress(user)) println(address)
Ora vorrei aggiungere la registrazione degli errori a questo for-comprehension
. Vorrei chiamare una funzione log(msg:String)
se uno o user
address
non viene trovato.
for(user <- findUser(id) ifNone log("user not found"); address <- findAddress(user) ifNone log("address not found")) println(address)
Posso farlo senza cambiare le firme di funzione?
Soluzione
Maybe
implicit def withIfNone[A](o: Option[A]) = new {
def ifNone(action: => Unit) = { if (o == None) action; o }
}
You may also consider using Either instead of option (or converting your options to Either). That would not work with a foreach (a for without a yield), but you might do
for(
a <- option1.toRight("option1 missing").right;
b <- option2.toRight("option2 missing").right)
yield f(a,b)
Then you can pattern match on the result with
case Left(error) => log (error)
case Right(result) => // use result
Altri suggerimenti
Lift's Box
is a more appropriate class for your usage case. A Box
is like an Option
, but with two empty states: ok and error. You could use it like this:
val addr = for {
user <- findUser(id) ?~ "user not found"
address <- findAddress(user) ?~ "address not found"
} yield address
address match {
case Full(addr) => println(addr)
case oops: Failure => println(oops.msg) // see Failure for more details
}
See this blog for various suggestions related to your problem.
It might be an overkill, but it looks pretty much like what you wanted ;)
object Extensions {
// You need a wrapper since Option is sealed
class OptionWrapper[E](option: Option[E]) {
def foreach[U](f: E => U) {
option foreach f
}
def isEmpty = option.isEmpty
}
// Modification trait for OptionWrapper
trait ErrorLogging[E] extends OptionWrapper[E] {
abstract override def foreach[U](f: E => U) {
if (isEmpty)
println("error")
else
super.foreach(f)
}
}
// Accessor for the new mixin
def log[E](option: Option[E]) = new OptionWrapper(option) with ErrorLogging[E]
}
object TestingLogger extends App {
case class User(address: String)
def findUser(id: Int): Option[User] = if (id == 1) Some(User("address")) else None
def findAddress(user: User): Option[String] = Some(user.address)
import Extensions._
for {
user <- log(findUser(1)) // prints out address
address <- log(findAddress(user))
} println(address)
for {
user <- log(findUser(2)) // prints out error
address <- log(findAddress(user))
} println(address)
}
If you have no idea of what just happened read this.