Scala 中方法类型参数化中的结构类型? [英] Structural type in method type parameterization in Scala?
问题描述
考虑以下 Scala 代码(例如,在 REPL 中)
Consider the following Scala code (e.g., in 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
前两个工作正常.第三个报错:
The first two work fine. The third ones gives an error:
错误:推断的类型参数 [ScalaObject] 不符合方法栏的类型参数边界 [T <: Any{def foo: Unit}]
有什么方法可以做我想做的事吗?
Are there any ways to do what I want?
推荐答案
这通常称为结构类型,而不是鸭子类型.我编辑了你的标题.:)
This is usually called structural typing, not duck typing. I edited your title. :)
我认为您的问题是由定义类型参数 T
然后以不变方式使用它引起的.T
只能引用一种具体类型,但是你有不同类型的参数A
和B
.
I think that your problem is caused by defining the type parameter T
and then using it in an invariant way. T
can only refer to one concrete type, but you have parameters of different types A
and B
.
这有效:
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
.替换后,这个例子和上面的完全一样.
This works because the compiler will simply substitute the structural type in place of its alias, T
. After the substitution, this example is exactly the same as the one above.
这篇关于Scala 中方法类型参数化中的结构类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!