简体   繁体   English

什么是 Scala 上下文和视图边界?

[英]What are Scala context and view bounds?

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!一些易于遵循的示例也很棒!

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 bound was a mechanism introduced in Scala to enable the use of some type A as if it were some type B .视图边界是 Scala 中引入的一种机制,用于启用某种类型A就好像它是某种类型B The typical syntax is this:典型的语法是这样的:

def f[A <% B](a: A) = a.bMethod

In other words, A should have an implicit conversion to B available, so that one can call B methods on an object of type A .换句话说, A应该有一个到B的隐式转换可用,以便可以在A类型的对象上调用B方法。 The most common usage of view bounds in the standard library (before Scala 2.8.0, anyway), is with Ordered , like this:标准库中视图边界的最常见用法(无论如何在 Scala 2.8.0 之前)是Ordered ,如下所示:

def f[A <% Ordered[A]](a: A, b: A) = if (a < b) a else b

Because one can convert A into an Ordered[A] , and because Ordered[A] defines the method <(other: A): Boolean , I can use the expression a < b .因为可以将A转换为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.它用于声明对于某些类型A ,有一个B[A]类型的隐式值可用。 The syntax goes like this:语法如下:

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 Array initialization on a parameterized type requires a ClassManifest to 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, implicitly is 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 library pattern, 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 .视图绑定使用的经典示例是处理Ordered Note that Int is not Ordered , for example, though there is an implicit conversion.请注意, Int不是Ordered ,例如,尽管存在隐式转换。 The example previously given needs a view bound because it returns the non-converted type:前面给出的示例需要一个视图边界,因为它返回未转换的类型:

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 f doesn't need to know about it.此处的转换(如果需要)发生在我将参数传递给f ,因此f不需要知道它。

Besides Ordered , the most common usage from the library is handling String and Array , which are Java classes, like they were Scala collections.除了Ordered之外,库中最常见的用法是处理StringArray ,它们是 Java 类,就像它们是 Scala 集合一样。 For example:例如:

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 String would be a WrappedString (Scala 2.8), and similarly for Array .如果试图在没有视图边界的情况下执行此操作,则String的返回类型将是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.上下文边界主要用于所谓的类型类模式,作为对 Haskell 类型类的引用。 Basically, this pattern implements an alternative to inheritance by making functionality available through a sort of implicit adapter pattern.基本上,该模式通过一种隐式适配器模式使功能可用,从而实现了继承的替代方案。

The classic example is Scala 2.8's Ordering , which replaced Ordered throughout Scala's library.经典的例子是 Scala 2.8 的Ordering ,它取代了整个 Scala 库中的Ordered The usage is:用法是:

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 Ordering that enable the traditional operator style.这利用了Ordering内部的一些隐式转换,这些转换支持传统的运算符样式。 Another example in Scala 2.8 is the Numeric : 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.一个更复杂的例子是CanBuildFrom的新集合用法,但已经有一个很长的答案,所以我会在这里避免它。 And, as mentioned before, there's the ClassManifest usage, which is required to initialize new arrays without concrete types.而且,如前所述,还有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.虽然它已经有很长一段时间了,但上下文边界的使用在 2010 年才真正开始流行,现在在 Scala 的大多数最重要的库和框架中都在一定程度上被发现。 The most extreme example of its usage, though, is the Scalaz library, which brings a lot of the power of Haskell to Scala.不过,最极端的例子是 Scalaz 库,它为 Scala 带来了 Haskell 的许多强大功能。 I recommend reading up on typeclass patterns to get more acquainted with all the ways in which it can be used.我建议阅读 typeclass 模式以更熟悉它的所有使用方式。

EDIT编辑

Related questions of interest:感兴趣的相关问题:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM