Apply 类型 [Scala] 中使用的方法

Apply method used in type [Scala]

我在浏览Scala代码,发现type中也使用了apply方法。

例子:
type Common = {
  def apply: {val func: {} => {val a: A}; val c: C} => {val b: B}
}

以上代码是什么意思?

据我了解,这意味着Common是指所有包含apply方法的类型。但是,问题是这意味着什么样的应用方法? apply 方法的输入应该是什么?

此外,

type Common = {
  def apply({val func: {} => {val a: A}; val c: C} => {val b: B})
}

两种普通类型有什么区别?

这称为结构类型。它只是意味着您通过其结构而不是(仅)通过其名称来描述类型。类型 Foo{val a: String} 表示 "something that has type Foo but also has a val a: String"。 {val a: String}AnyRef{val a: String} 相同。所以{}就是AnyRef{},和AnyRef.

的意思基本一样

当然你也可以在结构类型中使用结构类型,Common就是这样做的。 Common 是 AnyRef 的一个子类型,它有一个 apply 方法,它不接受任何参数,但是 returns 一个函数,它有一些复杂的结构类型作为类型参数。要破译那些你只需要递归地应用第一段中的规则。

您将如何使用这种 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

调用结构类型的方法也可能会产生运行时开销,因为它们是通过反射实现的。