Scala implicitly vs implicit arguments

我的梦境 提交于 2019-12-04 10:21:13

问题


I am new to Scala, and when I look at different projects, I see two styles for dealing with implicit arguments

scala]]>def sum[A](xs:List[A])(implicit m:Monoid[A]): A = xs.foldLeft(m.mzero)(m.mappend)
sum:[A](xs:List[A])(implicit m:Monoid[A])A

and

scala]]>def sum[A:Monoid](xs:List[A]): A ={
     val m = implicitly[Monoid[A]]
     xs.foldLeft(m.mzero)(m.mappend)
   }
sum:[A](xs:List[A])(implicit evidence$1:Monoid[A])A

Based off the type of both functions, they match. Is there a difference between the two? Why would you want to use implicitly over implicit arguments? In this simple example, it feels more verbose.

When I run the above in the REPL with something that doesn't have an implicit, I get the following errors

with implicit param

<console>:11: error: could not find implicit value for parameter m: Monoid[String]

and

with implicitly and a: Monoid

<console>:11: error: could not find implicit value for evidence parameter of type Monoid[String]

回答1:


In some circumstances, the implicit formal parameter is not directly used in the body of the method that takes it as an argument. Rather, it simply becomes an implicit val to be passed on to another method that requires an implicit parameter of the same (or a compatible) type. In that case, not having the overt implicit parameter list is convenient.

In other cases, the context bound notation, which is strictly syntactic sugar for an overt implicit parameter, is considered aesthetically desirable and even though the actual parameter is needed and hence the implicitly method must be used to get it is considered preferable.

Given that there is no semantic difference between the two, the choice is predicated on fairly subjective criteria.

Do whichever you like. Lastly note that changing from one to the other will not break any code nor would require recompilation (though I don't know if SBT is discriminting enough to forgo re-compiling code that can see the changed definition).



来源:https://stackoverflow.com/questions/22669233/scala-implicitly-vs-implicit-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!