0

我有简单的服务类

trait ItemService[+A] {
  def getItem(id: Int): Option[A]
}
class MockItemService(implicit inj: Injector) extends ItemService[Item] with Injectable      {
  def getItem(id: Int) =  {
     Option(new Feature("My Headline",Author(2,"Barry White")))
  }
}

使用 scaldi im 将 MockItemService 绑定到 ItemService 然后访问

class Features(implicit inj: Injector) extends Controller with Injectable {
   val itemService = inject [ItemService[Item]]
   def item(cat:String, id:Int, urlTitle:String) = Action {   
      itemService.getItem(id).map { item => Ok(views.html.feature.item(item))      
   }.getOrElse(NotFound)    
  }  
}

我想要的是项目的类型是功能而不是项目。功能扩展项目。

4

2 回答 2

0
    class Features(implicit inj: Injector) extends Controller with Injectable {
      val itemService = inject [ItemService[Item]]

      def item(cat:String, id:Int, urlTitle:String) = Action {
        itemService.getItem(id).map { item =>
           item match {
             case Feature(itsAFeature) => Ok(views.html.feature.item(itsAFeature))
             case itsAnItem => ???
           }
        }.getOrElse(NotFound)
      }
    }
于 2014-08-08T06:27:22.627 回答
0

I found this worked

  itemService.getItem(id).map { item =>
       item match {
         case x: Feature => Ok(views.html.feature.item(x))
         case _: Any => NotFound
       }
    }.getOrElse(NotFound)

It still feels a bit clunky. I basically want getItem to return different types of objects that are all sub types of Item but at some point i will need to deal with the specific type of object. I could do getFeature etc but i may not know the type before i call getItem. If the controller doesnt need to know the specifics then surely its a good idea it doesnt.

于 2014-08-09T20:31:38.263 回答