Scala中方法类型参数化的结构类型?

时间:2011-09-29 20:06:46

标签: scala

考虑以下Scala代码(例如,在REPL中)

object A{def foo:Unit = {}}
object B{def foo:Unit = {}}

def bar[T <: Any {def foo: Unit}](param: T*):Unit = param.foreach(x => x.foo)

bar(A, A)  // works fine
bar(B, B)  // works fine
bar(A, B)  // gives error

前两个工作正常。第三个出错:

error: inferred type arguments [ScalaObject] do not conform to method bar's type parameter bounds [T <: Any{def foo: Unit}]

有什么办法可以做我想要的吗?

1 个答案:

答案 0 :(得分:14)

这通常称为结构类型,而不是鸭子类型。我编辑了你的头衔。 :)

我认为您的问题是由定义类型参数T然后以不变的方式使用它引起的。 T只能引用一种具体类型,但您有不同类型的参数AB

这有效:

 def bar(param: {def foo: Unit}*) = param.foreach(x => x.foo)

编辑:使用类型别名也可以:

 type T = {def foo: Unit}
 def bar(param: T*) = param.foreach(x => x.foo)

这是有效的,因为编译器将简单地用结构类型代替其别名T。替换后,此示例与上面的示例完全相同。

相关问题