使用类型成员了解函数

时间:2016-02-04 01:27:06

标签: scala

假设:

scala> sealed trait FooWrapper[A] {
     |   type B = Int
     |   type C = List[A]
     | }
defined trait FooWrapper

是否有可能为此foo函数编译的合理实例?

scala> def foo[A](fooWrapper: FooWrapper[A]): fooWrapper.C = ???
foo: [A](fooWrapper: FooWrapper[A])fooWrapper.C

由于FooWrapper无法返回List[A],我认为不是。

1 个答案:

答案 0 :(得分:2)

这应该有效,不是吗?

sealed trait FooWrapper[A] {
   type B = Int
   type C = List[A]
}

class X(i:Int) extends FooWrapper[Int] { 
   def listify: C = List(i) 
}

def foo[A](fooWrapper: FooWrapper[A]): fooWrapper.C = fooWrapper match {
   case x: X => x.listify
   case _ => List()
}

使用它:

scala> foo(new X(2))
res1: List[Int] = List(2)
相关问题