Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How define the result type of this method?

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

like image 779
user816472 Avatar asked Jan 19 '23 09:01

user816472


1 Answers

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
}
like image 104
Aaron Novstrup Avatar answered Feb 13 '23 18:02

Aaron Novstrup