0

我正在尝试通过使用部分函数来实现/覆盖具有空输入参数的函数。这个不起作用的最小示例最好地解释了这一点:

trait T
trait TFactory {
  def build(): T
}

class A(someParameter: Int) extends T

object A extends TFactory {
  def build(someParameter: Int)(): T = new A(someParameter)
}

编译器抱怨:object creation impossible, since method build in trait TFactory of type ()T is not defined,这是有道理的,因为构建的类型是(Int)()T. 我的下一个想法是build明确地使函数的类型接受一个空参数并返回 a T,即:

trait T 
trait TFactory {
  def build: () => T    // what about empty parenthesis after build?
}

class A(someParameter: Int) extends T 

object A extends TFactory {
  def build(someParameter: Int): (() => T) = (() => new A(someParameter))
}

现在很明显 的类型build() => T。令我惊讶的是,编译器现在抱怨object creation impossible, since method build in trait TFactory of type => () => T is not defined(注意类型突然以 a 开头=>)。在函数定义的末尾拼命添加空括号也无济于事。

如何让我的编译器相信这些类型实际上是相同的?

澄清:

我的主要目标是实现无参数初始化,T而不需要工厂的工厂。例子:

val t = A(33).build()      // if this is possible, I though it might be possible to have:
val t = A.build(33)()

结论:

build我认为这是不可能的,因为抽象函数只是决定了函数必须采用多少个参数块。换句话说:你不能通过一个函数来实现一个抽象函数,它的部分应用恰好与你试图实现的函数具有相同的签名。

4

1 回答 1

1

I not exactly sure what you want to achieve. Let's say your TFactory was given as in your first example:

trait T

trait TFactory {
  def build(): T
}

Then the build method obviously cannot take any parameter. If you want to configure your factory, you can have a factory-factory:

class A(x: Int) extends T

object A {
  def apply(x: Int): TFactory = new TFactory {
    def build() = new A(x)
  }
}

val factory = A(33)
val t = factory.build()

If you define TFactory simply to be a function from () to T, you can use currying

type TFactory = () => T

object A {
  def apply(x: Int)(): T = new A(x)
}

val factory: TFactory = A(33) _
val t = factory()
于 2013-12-11T15:49:36.687 回答