什么是“上下文绑定"?在斯卡拉? [英] What is a "context bound" in Scala?

查看:48
本文介绍了什么是“上下文绑定"?在斯卡拉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 2.8 的新特性之一是上下文边界.什么是上下文绑定?它有什么用处?

One of the new features of Scala 2.8 are context bounds. What is a context bound and where is it useful?

当然我先搜索了(例如发现了this) 但我找不到任何真正清晰和详细的信息.

Of course I searched first (and found for example this) but I couldn't find any really clear and detailed information.

推荐答案

您是否找到了这篇文章?它在数组改进的上下文中涵盖了新的上下文绑定功能.

Did you find this article? It covers the new context bound feature, within the context of array improvements.

通常,具有上下文绑定的类型参数的形式为[T: Bound];它被扩展为普通类型参数 T 以及类型为 Bound[T] 的隐式参数.

Generally, a type parameter with a context bound is of the form [T: Bound]; it is expanded to plain type parameter T together with an implicit parameter of type Bound[T].

考虑方法 tabulate,它根据应用的结果形成一个数组在从 0 到给定长度的一系列数字上的给定函数 f.直到 Scala 2.7,表格可以是写成如下:

Consider the method tabulate which forms an array from the results of applying a given function f on a range of numbers from 0 until a given length. Up to Scala 2.7, tabulate could be written as follows:

def tabulate[T](len: Int, f: Int => T) = {
    val xs = new Array[T](len)
    for (i <- 0 until len) xs(i) = f(i)
    xs
}

在 Scala 2.8 中这不再可能,因为运行时信息是创建 Array[T] 的正确表示所必需的.需要通过将 ClassManifest[T] 作为隐式参数传递到方法中来提供此信息:

In Scala 2.8 this is no longer possible, because runtime information is necessary to create the right representation of Array[T]. One needs to provide this information by passing a ClassManifest[T] into the method as an implicit parameter:

def tabulate[T](len: Int, f: Int => T)(implicit m: ClassManifest[T]) = {
    val xs = new Array[T](len)
    for (i <- 0 until len) xs(i) = f(i)
    xs
}

作为一种简写形式,可以在类型参数 T 上使用 context bound 代替,给出:

As a shorthand form, a context bound can be used on the type parameter T instead, giving:

def tabulate[T: ClassManifest](len: Int, f: Int => T) = {
    val xs = new Array[T](len)
    for (i <- 0 until len) xs(i) = f(i)
    xs
}

这篇关于什么是“上下文绑定"?在斯卡拉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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