Scala方法依赖类型与密封参数

时间:2013-04-24 17:56:25

标签: scala

假设我有一些密封的课程

sealed abstract class SomeEnumThing {
    type RenderedType
}
object Type1 extends SomeEnumThing {
    type RenderedType = String
}
object Type2 extends SomeEnumThing  {
     type RenderedType = Array[Byte]
}

我希望根据传入的参数中定义的抽象类型返回一个方法,例如

def render(something : SomeEnumThing) : something.RenderedType = { .... }

这是什么语法。这甚至是可能的,我认为它与2.10方法相关的类型有关。

编辑:更新示例

sealed abstract class SomeThing {
    type RenderedType
}
object Type1 extends SomeThing {
    type RenderedType = String
}
object Type2 extends SomeThing  {
     type RenderedType = Long
}

def render(something : SomeThing) : something.RenderedType = 
  something match {
    case Type1 => "test"
    case Type2 => 0l
}

1 个答案:

答案 0 :(得分:0)

在结构上,你的例子中的内容似乎是正确的,但问题是你将在那些elipses中做什么来返回something.RenderedType。我快速投入一下来检查所有内容是否已编译(并且确实如此),但就像我说的那样,它归结为渲染函数内部的内容。这是我的代码:

object RenderedTypeTest {

  def render(something : SomeEnumThing) : something.RenderedType = {
    something.renderType
  }
}

sealed abstract class SomeEnumThing {
    type RenderedType
    def renderType:RenderedType
}
object Type1 extends SomeEnumThing {
    type RenderedType = String
    def renderType = "hello"
}
object Type2 extends SomeEnumThing  {
     type RenderedType = Array[Byte]
     def renderType = Array()
}