什么时候应该在Scala中使用隐式参数创建方法? [英] When should I make methods with implicit argument in Scala?

查看:99
本文介绍了什么时候应该在Scala中使用隐式参数创建方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用scala中的play框架编写了如下代码:

I made codes using play framework in scala which look like the following:

object Application extends Controller {
  def hoge = Action( implicit request =>
    val username = MyCookie.getName.get
    Ok("hello " + username)
  }
}

object MyCookie {
  def getName( implicit request: RequestHeader ) = {
    request.cookies.get("name").map(_.value)
  }
}

我的同事收到了代码审查.他说,由于隐式参数,该代码不可读.我无法回复他的意见.那么,您能告诉我使用隐式参数的最佳方法是什么吗?什么时候应该使用隐式参数?

I got a code review from my coworker. He said this code is not readable because of implicit parameter. I couldn't reply to his opinion. So could you tell me what is the best way to use implicit parameters? When should I use implicit parameters?

推荐答案

当几乎总是有一种正确"的方式来做事情,而您几乎一直想忽略那些细节时,应该使用隐式参数.或通常没有 做事情的方式,而隐式函数为那些起作用的事情提供了功能.

You should use implicit parameters when there is almost always a "right" way to do things, and you want to ignore those details almost all the time; or when there often is no way to do things, and the implicits provide the functionality for those things that work.

对于第一种情况的示例,在scala.concurrent.Future中,几乎每种方法都采用隐式的ExecutionContext.您几乎从不在乎您的ExecutionContext是从一个呼叫到另一个呼叫的含义.您只希望它能正常工作.但是,当您需要更改执行上下文时,可以将其作为显式参数提供.

For an example of the first case, in scala.concurrent.Future, almost every method takes an implicit ExecutionContext. You almost never care what your ExecutionContext is from call to call; you just want it to work. But when you need to change the execution context you can supply it as an explicit parameter.

有关第二种情况的示例,请查看集合库中的CanBuildFrom.您不能从任何东西中构建出任何东西.提供了某些功能,而缺少使您将一堆Vector[Option[String]]打包成HashSet[Char]的隐式函数,是保持库功能强大,灵活而又理智的一种主要方法.

For an example of the second case, look at the CanBuildFroms in the collections library. You cannot build anything from anything; certain capabilities are supplied, and the lack of an implicit that, say, lets you package up a bunch of Vector[Option[String]]s into a HashSet[Char] is one major way to keep the library powerful and flexible yet sane.

您什么都不做:显然,您只是在使用它来节省一点输入,而牺牲了另一点.而且,在这种情况下,这样做使事情的工作方式变得不那么明显,因为您必须四处张望,以找出隐式请求的实际使用位置.如果要保存类型,最好使用简短的变量名,但要明确一些:

You are doing neither: apparently you're just using it to save a little typing in one spot at the expense of the other spot. And, in this case, in doing so you've made it less obvious how things work, as you have to look all over the place to figure out where that implicit request actually gets used. If you want to save typing, you're much better off using short variable names but being explicit about it:

Action{ req => val name = MyCookie.getName(req).get; Ok("hello "+name) }

这篇关于什么时候应该在Scala中使用隐式参数创建方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆