我有一个方法,用有很多隐含参数的内隐:模式匹配
def hello(message:String)(implicit a:A,b:B,c:C, ..., user: User) = {...}
现在考虑这样一个类:
object Users extends Controller {
implicit a: A = ...
implicit b: B = ...
...
def index(id:String) = Action {
User.findById(id) match {
case Some(user) => {
implicit val _user = user
hello("implicit")
}
case _ => BadRequest
}
}
}
你可以看到在上面的示例中这行:
implicit val _user = user
它的存在只是为了让对象user
作为隐含对象。否则,我要叫hello
为:
hello("implicit")(a,b,c,... user)
我在想,如果有任何的方式来提高代码,例如我们不需要定义_user
变量,但使user
是隐含的。
+1,如果模式匹配“Option”,这是一个很好的解决方案。但是如果有很多案例呢? – Freewind 2012-03-10 03:38:05
@Freewind。我已经更新了我的答案,涵盖了许多“案例”。 – romusz 2012-03-10 19:50:55