【问题标题】:scala type 'extraction'scala类型'提取'
【发布时间】:2012-08-19 02:40:58
【问题描述】:

这可能不是最正确的术语,但我所说的盒装类型是 Box[T] 用于类型 T。所以Option[Int] 是一个盒装的Int

如何提取这些类型?我天真的尝试:

//extractor
type X[Box[E]] = E //doesn't compile. E not found

//boxed
type boxed = Option[Int]

//unboxed
type parameter = X[boxed] //this is the syntax I would like to achieve
implicitly[parameter =:= Int] //this should compile

有没有办法做到这一点?除了 Apocalisp 博客之外,我很难找到有关 Scala 中类型级元编程的说明。

【问题讨论】:

  • 哪一个用例是你有更高种类的类型(你称之为'boxed')但没有它的类型参数?我无法想象您的parameter 会出现或有用的任何场景?
  • 这更像是对 scala 类型系统的探索,我没有任何用例

标签: scala types type-systems unboxing


【解决方案1】:

我只能想象两种情况。要么使用类型参数,要么使用这种更高种类的类型,例如作为方法的参数,您将在方法泛型中复制其类型参数:

trait Box[E]

def doSomething[X](b: Box[X]) { ... } // parameter re-stated as `X`

或者你有类型成员,那么你可以在每个实例中引用它们:

trait Box { type E }

def doSomething(b: Box) { type X = b.E }

...一般来说

def doSomething(x: Box#E) { ... }

所以我认为你需要根据你真正想要实现的目标来重写你的问题。

【讨论】:

    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2013-01-26
    • 2022-01-08
    • 2021-10-15
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多