How do I define the method return type in the following case:
working code
def deleteInstance(model: String, uid: Long) = model match {
case "menu" => Model.all(classOf[Menu]).filter("uid", uid).get().delete()
case "articles" => Model.all(classOf[Articles]).filter("uid", uid).get().delete()
case "news" => Model.all(classOf[News]).filter("uid", uid).get().delete()
case "image" =>Model.all(classOf[Image]).filter("uid", uid).get().delete()
case "files" =>Model.all(classOf[Files]).filter("uid", uid).get().delete()
case _ => false
}
non-working code:
class ModelManager{
def getModel(model: String) = {
model match{
case "menu" => classOf[Menu]
case "articles" => classOf[Articles]
case _ => false
}
def deleteInstance(model:String, uid: Long) = {
Model.all(getModel(model)).filter("uid", uid).get().delete()
}
}
}
Error raised is:
recursive method getModel needs result type
It looks like you need an Option:
class ModelManager{
def getModel(model: String) = model match {
case "menu" => Some(classOf[Menu])
case "articles" => Some(classOf[Articles])
case _ => None
}
def deleteInstance(model:String, uid: Long) =
getModel(model) map { m =>
Model.all(m).filter("uid", uid).get().delete()
} getOrElse false
}
You can think of an Option as a container that can hold at most one element. The Option that holds an element x
is Some(x)
. The empty Option is None
. Option has several useful methods, including the map
and getOrElse
methods used above.
The map
method applies a function to each element of the "container". Of course, if the container is None
, it does nothing (except perhaps to change the static type of the Option). In your case (assuming delete
returns a Boolean), the map method will change the Option[Class] into an Option[Boolean].
The getOrElse
method returns the element of the option, if there is one, and otherwise returns a default value (false
in this case).
Note that you can also simplify your implementation by using the condOpt
method defined in PartialFunction:
class ModelManager{
def getModel(model: String) = condOpt(model) {
case "menu" => classOf[Menu]
case "articles" => classOf[Articles]
}
def deleteInstance(model:String, uid: Long) =
getModel(model) map { m =>
Model.all(m).filter("uid", uid).get().delete()
} getOrElse false
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With