在 scalaz 中使用视图边界
我第一次尝试 scalaz,将现有的类转换为使用 Monoid 特征。我想要实现的是在我的类类型参数上设置一个视图绑定,以确保它只能与可以隐式转换为 Monoid 的类型一起使用。我的(简化的)类定义是这样的:
import scalaz._
import Scalaz._
case class Foo[T <% Monoid[T]](v: T)
new Foo(42)
编译这个简单的例子会给出编译器错误:
error: No implicit view available from Int => scalaz.Monoid[Int].
以前这个视图绑定是根据我自己的自定义特征定义的,并从 T 到特征的隐式转换,这工作得很好。
现在我已经将其转换为 scalaz,我缺少什么?
谢谢, 克里斯
I'm taking my first foray into scalaz by converting an existing class to use the Monoid trait. What I am trying to achieve is to set a view bound on my class type parameter to ensure that it can only be used with types that can be implicitly converted to a Monoid. My (simplified) class definition is thus:
import scalaz._
import Scalaz._
case class Foo[T <% Monoid[T]](v: T)
new Foo(42)
Compiling this simple example gives the compiler error:
error: No implicit view available from Int => scalaz.Monoid[Int].
Previously this view bound was defined against my own custom trait with an implicit conversion from T to the trait and this worked fine.
What am I missing now that I have converted this to scalaz?
Thanks,
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用上下文绑定,而不是那里的视图绑定。
T : Monoid
表示法意味着作用域中存在隐式的Monoid[T]
类型。事实上,它脱糖如下:这称为类型类模式,您可以阅读有关它的更多信息 此处。
You are supposed to be using a context bound, and not a view bound there.
The
T : Monoid
notation means that there is an implicit of typeMonoid[T]
in scope. In fact, it desugars to the following:This is known as type class pattern and you can read more about it here.