具有更高种类类型的上下文边界快捷方式 [英] Context bounds shortcut with higher kinded-types

查看:75
本文介绍了具有更高种类类型的上下文边界快捷方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将上下文边界语法快捷方式用于更高种类的类型?

Is it possible to use the context bounds syntax shortcut with higher kinded-types?

trait One { def test[W   : ClassManifest]: Unit } // first-order ok
trait Two { def test[W[_]: ClassManifest]: Unit } // not possible??
trait Six { def test[W[_]](implicit m: ClassManifest[W[_]]): Unit } // hmm...

推荐答案

是的,但是您的上下文绑定类型必须具有更高种类的类型参数(ClassManifest没有).

Yes, it is, but your context bound type must have a higher kinded type parameter (which ClassManifest doesn't).

scala> trait HKTypeClass[CC[_]]
defined trait HKTypeClass

scala> implicit def listHKTC = new HKTypeClass[List] {}
listHKTC: java.lang.Object with HKTypeClass[List]

scala> def frob[CC[_] : HKTypeClass] = implicitly[HKTypeClass[CC]]
frob: [CC[_]](implicit evidence$1: HKTypeClass[CC])HKTypeClass[CC]

scala> frob[List]
res0: HKTypeClass[List] = $anon$1@13e02ed

更新

可以使用类型别名来允许类型较高的类型参数以一阶上下文绑定类型为边界.我们使用类型别名作为类型级别的函数,以从一阶类型中产生更高种类的类型.对于ClassManifest,它可能会这样,

It's possible to use a type alias to allow a higher-kinded type parameter to be bounded by a first-order context bound type. We use the type alias as a type-level function to make a higher-kinded type out of the first-order type. For ClassManifest it could go like this,

scala> type HKClassManifest[CC[_]] = ClassManifest[CC[_]]
defined type alias HKClassManifest

scala> def frob[CC[_] : HKClassManifest] = implicitly[HKClassManifest[CC]]         
test: [CC[_]](implicit evidence$1: HKClassManifest[CC])HKClassManifest[CC]

scala> frob[List]                                                       
res1: HKClassManifest[List] = scala.collection.immutable.List[Any]

请注意,类型别名CC [_]的右侧是一阶类型,这里的下划线是通配符.因此,它可用作ClassManifest的类型参数.

Note that on the right hand side of the type alias CC[_] is a first-order type ... the underscore here is the wildcard. Consequently it can be used as the type argument for ClassManifest.

更新

为完整起见,我应注意,可以使用lambda类型内联类型别名,

For completeness I should note that the type alias can be inlined using a type lambda,

scala> def frob[CC[_] : ({ type λ[X[_]] = ClassManifest[X[_]] })#λ] = implicitly[ClassManifest[CC[_]]]     
frob: [CC[_]](implicit evidence$1: scala.reflect.ClassManifest[CC[_]])scala.reflect.ClassManifest[CC[_]]

scala> frob[List]
res0: scala.reflect.ClassManifest[List[_]] = scala.collection.immutable.List[Any]

这篇关于具有更高种类类型的上下文边界快捷方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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