加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Scala中约束更高层次的类型

发布时间:2020-12-16 19:19:51 所属栏目:安全 来源:网络整理
导读:说我有更高的kinded类型 SuperMap[Key[_],Value[_]]`. 现在假设我有一些更具体的东西,要求Key的type参数必须与Value匹配;就是这样的: SuperDuperMap[T,Key[T],Value[T]] 进一步假设我不想要任何T,而是一个非常具体的T,其中T:OtherT SuperDuperPooperMap[T
说我有更高的kinded类型

SuperMap[Key[_],Value[_]]`.

现在假设我有一些更具体的东西,要求Key的type参数必须与Value匹配;就是这样的:

SuperDuperMap[T,Key[T],Value[T]]

进一步假设我不想要任何T,而是一个非常具体的T,其中T<:OtherT

SuperDuperPooperMap[T <: OtherT,Value[T]]

这可以在Scala中完成吗?这通常是一个坏主意吗?有没有相同的方法来做这个更容易阅读/写/使用?

解决方法

你的声明已经按照预期的方式工作,即你限制了T的类型以及Key和Value.但是,如果你发出类似的话,scala会抱怨你写的方式

scala> class Foo[T <: OtherT,Value[T]]
defined class Foo

scala> new Foo[SpecialOtherT,Key[SpecialOtherT],Value[SpecialOtherT]]
<console>:13: error: Key[SpecialOtherT] takes no type parameters,expected: one
              new Foo[SpecialOtherT,Value[SpecialOtherT]]

因为您的前声明已经给出了Key和Value的类型.因此,这将有效

scala> new Foo[SpecialOtherT,Key,Value]
res20: Foo[SpecialOtherT,Value] = Foo@3dc6a6fd

这可能不是你想要的.你可以这样做

scala> class Foo[T <: OtherT,K <: Key[T],V <: Value[T]]
defined class Foo

scala> new Foo[SpecialOtherT,Value[SpecialOtherT]]
res21: Foo[SpecialOtherT,Value[SpecialOtherT]] = Foo@7110506e

在底线,由于Key和Value的类型完全取决于T,因此在使用Foo时获得所有冗余信息有点多余.那么为什么不使用这样的内部类型声明:

class Foo[T <: OtherT] {
  type K = Key[T]
  type V = Value[T]
}

然后,您可以从类中访问类型K和V,但每次创建新答案时都不需要键入它:

scala> new Foo[SpecialOtherT]
res23: Foo[SpecialOtherT] = Foo@17055e90

scala> new Foo[Int]
<console>:11: error: ...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读