什么是 Scala 上下文和视图边界?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4465948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are Scala context and view bounds?
提问by chrsan
In a simple way, what are context and view bounds and what is the difference between them?
简单来说,上下文和视图边界是什么,它们之间有什么区别?
Some easy-to-follow examples would be great too!
一些易于遵循的示例也很棒!
回答by Daniel C. Sobral
I thought this was asked already, but, if so, the question isn't apparent in the "related" bar. So, here it is:
我认为这已经被问到了,但是,如果是这样,这个问题在“相关”栏中并不明显。所以,这里是:
What is a View Bound?
什么是视图边界?
A view boundwas a mechanism introduced in Scala to enable the use of some type Aas ifit were some type B. The typical syntax is this:
甲绑定视图是在Scala中引入,以便能够使用某种类型的机制A,就好像它是一些类型B。典型的语法是这样的:
def f[A <% B](a: A) = a.bMethod
In other words, Ashould have an implicit conversion to Bavailable, so that one can call Bmethods on an object of type A. The most common usage of view bounds in the standard library (before Scala 2.8.0, anyway), is with Ordered, like this:
换句话说,A应该隐式转换为B可用,以便可以调用B类型对象的方法A。标准库中视图边界的最常见用法(无论如何在 Scala 2.8.0 之前)是 with Ordered,如下所示:
def f[A <% Ordered[A]](a: A, b: A) = if (a < b) a else b
Because one can convert Ainto an Ordered[A], and because Ordered[A]defines the method <(other: A): Boolean, I can use the expression a < b.
因为可以转换A为 an Ordered[A],并且因为Ordered[A]定义了方法<(other: A): Boolean,所以我可以使用表达式a < b。
Please be aware that view bounds are deprecated, you should avoid them.
请注意,不推荐使用视图边界,您应该避免使用它们。
What is a Context Bound?
什么是上下文绑定?
Context bounds were introduced in Scala 2.8.0, and are typically used with the so-called type class pattern, a pattern of code that emulates the functionality provided by Haskell type classes, though in a more verbose manner.
上下文边界是在 Scala 2.8.0 中引入的,通常与所谓的类型类模式一起使用,这是一种模拟 Haskell 类型类提供的功能的代码模式,但方式更为冗长。
While a view bound can be used with simple types (for example, A <% String), a context bound requires a parameterized type, such as Ordered[A]above, but unlike String.
虽然视图绑定可以与简单类型(例如,A <% String)一起使用,但上下文绑定需要参数化类型,例如Ordered[A]上面的,但与String.
A context bound describes an implicit value, instead of view bound's implicit conversion. It is used to declare that for some type A, there is an implicit value of type B[A]available. The syntax goes like this:
上下文绑定描述的是隐式值,而不是视图绑定的隐式转换。它用于声明对于某些类型A,存在类型的隐式值B[A]可用。语法如下:
def f[A : B](a: A) = g(a) // where g requires an implicit value of type B[A]
This is more confusing than the view bound because it is not immediately clear how to use it. The common example of usage in Scala is this:
这比视图边界更令人困惑,因为它并不清楚如何使用它。Scala 中常见的用法示例如下:
def f[A : ClassManifest](n: Int) = new Array[A](n)
An Arrayinitialization on a parameterized type requires a ClassManifestto be available, for arcane reasons related to type erasure and the non-erasure nature of arrays.
由于与类型擦除和数组的非擦除性质相关的神秘原因,Array参数化类型的初始化需要ClassManifest可用。
Another very common example in the library is a bit more complex:
库中另一个非常常见的例子有点复杂:
def f[A : Ordering](a: A, b: A) = implicitly[Ordering[A]].compare(a, b)
Here, implicitlyis used to retrive the implicit value we want, one of type Ordering[A], which class defines the method compare(a: A, b: A): Int.
在这里,implicitly用于检索我们想要的隐式值,类型之一Ordering[A],哪个类定义了方法compare(a: A, b: A): Int。
We'll see another way of doing this below.
我们将在下面看到另一种方法。
How are View Bounds and Context Bounds implemented?
视图边界和上下文边界是如何实现的?
It shouldn't be surprising that both view bounds and context bounds are implemented with implicit parameters, given their definition. Actually, the syntax I showed are syntactic sugars for what really happens. See below how they de-sugar:
鉴于它们的定义,视图边界和上下文边界都是使用隐式参数实现的,这不足为奇。实际上,我展示的语法是真正发生的事情的语法糖。看看下面他们是如何脱糖的:
def f[A <% B](a: A) = a.bMethod
def f[A](a: A)(implicit ev: A => B) = a.bMethod
def g[A : B](a: A) = h(a)
def g[A](a: A)(implicit ev: B[A]) = h(a)
So, naturally, one can write them in their full syntax, which is specially useful for context bounds:
因此,很自然地,人们可以用完整的语法编写它们,这对于上下文边界特别有用:
def f[A](a: A, b: A)(implicit ord: Ordering[A]) = ord.compare(a, b)
What are View Bounds used for?
视图边界有什么用?
View bounds are used mostly to take advantage of the pimp my librarypattern, through which one "adds" methods to an existing class, in situations where you want to return the original type somehow. If you do not need to return that type in any way, then you do not need a view bound.
视图边界主要用于利用我的库模式的皮条客模式,在您想以某种方式返回原始类型的情况下,通过该模式可以向现有类“添加”方法。如果您不需要以任何方式返回该类型,那么您就不需要视图绑定。
The classic example of view bound usage is handling Ordered. Note that Intis not Ordered, for example, though there is an implicit conversion. The example previously given needs a view bound because it returns the non-converted type:
视图绑定使用的经典示例是处理Ordered. 请注意,Int不是Ordered,例如,尽管存在隐式转换。前面给出的示例需要一个视图边界,因为它返回未转换的类型:
def f[A <% Ordered[A]](a: A, b: A): A = if (a < b) a else b
This example won't work without view bounds. However, if I were to return another type, then I don't need a view bound anymore:
如果没有视图边界,此示例将无法工作。但是,如果我要返回另一种类型,则不再需要视图绑定:
def f[A](a: Ordered[A], b: A): Boolean = a < b
The conversion here (if needed) happens before I pass the parameter to f, so fdoesn't need to know about it.
此处的转换(如果需要)发生在我将参数传递给 之前f,因此f不需要了解它。
Besides Ordered, the most common usage from the library is handling Stringand Array, which are Java classes, like they were Scala collections. For example:
此外Ordered,库中最常见的用法是处理String和Array,它们是 Java 类,就像它们是 Scala 集合一样。例如:
def f[CC <% Traversable[_]](a: CC, b: CC): CC = if (a.size < b.size) a else b
If one tried to do this without view bounds, the return type of a Stringwould be a WrappedString(Scala 2.8), and similarly for Array.
如果试图在没有视图边界的情况下执行此操作,则 a 的返回类型String将是 a WrappedString(Scala 2.8),对于Array.
The same thing happens even if the type is only used as a type parameter of the return type:
即使该类型仅用作返回类型的类型参数,也会发生同样的事情:
def f[A <% Ordered[A]](xs: A*): Seq[A] = xs.toSeq.sorted
What are Context Bounds used for?
上下文边界有什么用?
Context bounds are mainly used in what has become known as typeclass pattern, as a reference to Haskell's type classes. Basically, this pattern implements an alternative to inheritance by making functionality available through a sort of implicit adapter pattern.
上下文边界主要用于所谓的类型类模式,作为对 Haskell 类型类的引用。基本上,此模式通过一种隐式适配器模式使功能可用,从而实现了继承的替代方案。
The classic example is Scala 2.8's Ordering, which replaced Orderedthroughout Scala's library. The usage is:
经典的例子是 Scala 2.8 的Ordering,它Ordered在整个 Scala 的库中都被替换了。用法是:
def f[A : Ordering](a: A, b: A) = if (implicitly[Ordering[A]].lt(a, b)) a else b
Though you'll usually see that written like this:
虽然你通常会看到这样写:
def f[A](a: A, b: A)(implicit ord: Ordering[A]) = {
import ord.mkOrderingOps
if (a < b) a else b
}
Which take advantage of some implicit conversions inside Orderingthat enable the traditional operator style. Another example in Scala 2.8 is the Numeric:
它利用内部的一些隐式转换Ordering来启用传统的运算符样式。Scala 2.8 中的另一个例子是Numeric:
def f[A : Numeric](a: A, b: A) = implicitly[Numeric[A]].plus(a, b)
A more complex example is the new collection usage of CanBuildFrom, but there's already a very long answer about that, so I'll avoid it here. And, as mentioned before, there's the ClassManifestusage, which is required to initialize new arrays without concrete types.
一个更复杂的例子是 的新集合用法CanBuildFrom,但已经有一个很长的答案,所以我会在这里避免它。而且,如前所述,还有一个ClassManifest用法,它是初始化没有具体类型的新数组所必需的。
The context bound with the typeclass pattern is much more likely to be used by your own classes, as they enable separation of concerns, whereas view bounds can be avoided in your own code by good design (it is used mostly to get around someone else's design).
与 typeclass 模式绑定的上下文更有可能被您自己的类使用,因为它们可以实现关注点分离,而通过良好的设计可以在您自己的代码中避免视图边界(它主要用于绕过其他人的设计) )。
Though it has been possible for a long time, the use of context bounds has really taken off in 2010, and is now found to some degree in most of Scala's most important libraries and frameworks. The most extreme example of its usage, though, is the Scalaz library, which brings a lot of the power of Haskell to Scala. I recommend reading up on typeclass patterns to get more acquainted with all the ways in which it can be used.
尽管这已经有很长一段时间了,但上下文边界的使用在 2010 年才真正开始流行,现在在 Scala 的大多数最重要的库和框架中都在一定程度上得到了使用。然而,其使用最极端的例子是 Scalaz 库,它为 Scala 带来了 Haskell 的许多强大功能。我建议阅读 typeclass 模式以更熟悉它的所有使用方式。
EDIT
编辑
Related questions of interest:
感兴趣的相关问题:

