这被称为结构类型。它只是意味着您通过其结构而不是(仅)通过其名称来描述类型。类型的Foo{val a: String}
意思是“有类型Foo
但也有”的东西val a: String
。{val a: String}
是一样的AnyRef{val a: String}
。so的{}
意思AnyRef{}
,基本上和 的意思一样AnyRef
。
当然你也可以在结构类型中使用结构类型,就是Common
这样。Common
是 AnyRef 的一个子类型,它有一个apply
不接受参数但返回一个具有一些复杂结构类型作为类型参数的函数的方法。要破译那些你只需要递归地应用第一段中的规则。
你会如何使用这种Common
类型?我建议不要,但是...
scala> :paste
// Entering paste mode (ctrl-D to finish)
class A; class B; class C
type Common = {
def apply: {val func: {} => {val a: A}; val c: C} => {val b: B}
}
class HasA { val a = new A }
class HasB { val b = new B }
class HasC {
val func = (a: AnyRef) => new HasA
val c = new C
}
class MyCommon { def apply = (h: Any) => new HasB }
// Exiting paste mode, now interpreting.
scala> def common(c: Common) = c
common: (c: Common)Common
scala> common(new MyCommon)
res0: Common = MyCommon@3652a0d8
scala> res0.apply(new HasC)
res1: AnyRef{val b: B} = HasB@3925c40e
scala> res1.b
res2: B = B@1ba053df
调用结构类型的方法也可能会产生运行时开销,因为它们是通过反射实现的。