如何获取与上下文绑定关联的类型类的实例? [英] How do I get an instance of the type class associated with a context bound?

查看:35
本文介绍了如何获取与上下文绑定关联的类型类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我提出这个问题是为了自己回答,但欢迎其他答案.

考虑以下简单方法:

def add[T](x: T, y: T)(implicit num: Numeric[T]) = num.plus(x,y)

我可以使用上下文绑定重写此内容,如下

I can rewrite this using a context bound as follows

def add[T: Numeric](x: T, y: T) = ??.plus(x,y) 

但是我如何获得 Numeric[T] 类型的实例以便我可以调用 plus 方法?

but how do I get an instance of the Numeric[T] type so that I can invoke the plus method?

推荐答案

使用隐式方法

Using the implicitly method

最常见和通用的方法是使用在 Predef 中定义的 隐式方法:>

The most common and general approach is to use the implicitly method, defined in Predef:

def add[T: Numeric](x: T, y: T) = implicitly[Numeric[T]].plus(x,y)

显然,这有点冗长,需要重复类型类的名称.

Obviously, this is somewhat verbose and requires repeating the name of the type class.

引用证据参数(不要!)

另一种选择是使用编译器自动生成的隐式证据参数的名称:

Another alternative is to use the name of the implicit evidence parameter automatically generated by the compiler:

def add[T: Numeric](x: T, y: T) = evidence$1.plus(x,y)

令人惊讶的是,这种技术甚至是合法的,在实践中不应依赖它,因为证据参数的名称可能会改变.

It's surprising that this technique is even legal, and it should not be relied upon in practice since the name of the evidence parameter could change.

高级上下文(介绍context方法)

相反,可以使用 implicitly 方法的增强版本.注意隐式方法定义为

Instead, one can use a beefed-up version of the implicitly method. Note that the implicitly method is defined as

def implicitly[T](implicit e: T): T = e

这个方法简单地依赖编译器从周围的作用域中插入一个正确类型的隐式对象到方法调用中,然后返回它.我们可以做得更好:

This method simply relies on the compiler to insert an implicit object of the correct type from the surrounding scope into the method call, and then returns it. We can do a bit better:

def context[C[_], T](implicit e: C[T]) = e

这允许我们将 add 方法定义为

This allows us to define our add method as

def add[T: Numeric](x: T, y: T) = context.plus(x,y)

context 方法类型参数NumericT 是从作用域推断出来的!不幸的是,在某些情况下,此 context 方法将不起作用.例如,当一个类型参数有多个上下文边界或有多个参数具有不同的上下文边界时.我们可以用稍微复杂一点的版本来解决后一个问题:

The context method type parameters Numeric and T are inferred from the scope! Unfortunately, there are circumstances in which this context method will not work. When a type parameter has multiple context bounds or there are multiple parameters with different context bounds, for example. We can resolve the latter problem with a slightly more complex version:

class Context[T] { def apply[C[_]]()(implicit e: C[T]) = e }
def context[T] = new Context[T]

这个版本要求我们每次都指定类型参数,但是处理多个类型参数.

This version requires us to specify the type parameter every time, but handles multiple type parameters.

def add[T: Numeric](x: T, y: T) = context[T]().plus(x,y)

这篇关于如何获取与上下文绑定关联的类型类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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