Scala隐式vs隐式参数 [英] Scala implicitly vs implicit arguments

查看:145
本文介绍了Scala隐式vs隐式参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Scala的新手,当我查看不同的项目时,我看到了两种处理隐式参数的样式

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

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.

当我在REPL中使用没有隐式内容的代码运行上述代码时,出现以下错误

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

具有隐式参数

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

带有隐式和a:Monoid

with implicitly and a: Monoid

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

推荐答案

在某些情况下,隐式形式参数未直接在将其用作参数的方法主体中使用.而是,它简单地变成了一个隐式val,以传递给另一个需要相同(或兼容)类型的隐式参数的方法.在这种情况下,不使用公开的隐式参数列表会很方便.

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.

在其他情况下,上下文绑定表示法(对于明显的隐式参数严格来说是语法糖)在美学上被认为是理想的,即使需要实际参数,因此也必须使用implicitly方法来获取它更好.

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.

做任何你想做的事.最后请注意,从一个更改为另一个不会破坏任何代码,也不需要重新编译(尽管我不知道SBT是否具有足够的区分性,以致放弃重新编译可以看到更改的定义的代码).

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).

这篇关于Scala隐式vs隐式参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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