关于 Scala 中视图的问题
我看到了一些例子,其中转换函数 T =>; S
作为隐式参数传递。 Scala 调用这个函数view
,甚至提供特殊的语法糖 - - 视图绑定
- 对于这种情况。
然而我们已经有了隐式转换!我可以用隐式转换替换这些视图
(即作为隐式参数传递的转换函数)吗? ?我可以使用 views
做什么而不能使用隐式转换?
I saw examples, where a conversion function T => S
is passed as an implicit parameter. Scala calls this function view
and even provides special syntax sugar -- view bound
-- for that case .
However we already have implicit conversions ! Can I replace these views
(i.e. conversion functions passed as implicit parameters) with implicit conversions ? ? What I can do with views
what I can't with implicit conversions ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“是”有什么优势
我对你的问题的理解是,相对于
?视图的含义正是这样:类型 T 可以被视为另一种类型 S。您的方法或函数可能希望首先处理 T。一个例子是 Ordered:
视图边界的另外两个用例:
(这在某种程度上与上面的情况相同:您基本上想要使用 T)
My understanding of your question is, what would be the advantage of
over
Yes? Well the meaning of view is exactly that: the type T can be viewed as another type S. Your method or function might want to deal with T in the first place. An example is Ordered:
Two more use cases for view bounds:
(this is in a way the same situation as above: you basically want to work with T)
您所说的隐式转换只不过是全局范围内的视图。
使用类型参数时,视图边界是必要的,因为它是需要隐式转换的标志。例如:
因为
T
上没有任何约束,所以编译器不知道<
方法可用。让我们看看编译器是否允许您继续执行此操作,然后考虑这两个调用:签名
max[T](a: T, b: T): T
中没有任何内容告诉编译器应该这样做不允许第二次调用,但应该允许第一次。这就是视图边界的用武之地:它不仅告诉编译器
<
方法来自哪里,还告诉编译器max(true, false)
不是有效的。What you call implicit conversions is nothing more than a view in global scope.
View bounds are necessary in when using type parameters, as it is a sign that an implicit conversion is necessary. For example:
Because there's no constrains whatsoever on
T
, the compiler doesn't know that a<
method will be available. Let's see the compiler let you go ahead with that, then consider these two calls:There's nothing in the signature
max[T](a: T, b: T): T
that tells the compiler it should not allow the second call, but should allow the first. This is where view bounds come in:That not only tells the compiler where the
<
method comes from, but also tells the compiler thatmax(true, false)
is not valid.