Scala:与 (Any*) => Unit 类型不匹配
Scala: type mismatch with (Any*) => Unit
我有一个抽象方法
def updateState: (Any*) => Unit
我试图通过以下方式在 child class 中覆盖:
override def updateState = (sharedOptimizer: Vector[Double],
sharedMeanGradient: Vector[Double],
sharedHistoricalGradients: Array[Vector[Double]]) => {
()
}
我不明白为什么编译器returns我这个错误:
Error:(75, 81) type mismatch;
found : (Vector[Double], Vector[Double], Array[Vector[Double]]) => Unit
required: Any* => Unit
类型 Any*
不是应该表示 "any number of arguments of any type" 吗?
类型Any*
只是一个普通类型,就像Int
或List[String]
一样。
就像你不能覆盖一个方法一样
def foo(x: List[String]): Unit
来自
def foo(x: Int): Unit
你也可以不覆盖
def updateState: (Any*) => Unit
来自
def updateState:
(Vector[Double], Vector[Double], Array[Vector[Double]]) => Unit
因为 (Vec[D], Vec[D], Arr[Vec[D]])
不是 Any*
的超类型,即有很多东西可以作为 Any*
传递,而不是 (Vec[D], Vec[D], Arr[Vec[D]])
.
如果您不想立即对状态类型进行硬编码,请用它来参数化您的 class:
trait Foo[S] {
def updateState: S => Unit
}
或使其成为类型成员:
trait Foo {
type State
def updateState: State => Unit
}
然后你可以在 subclasses:
中覆盖它
object Bar extends Foo[Int] {
override def updateState: Int => Unit =
x => println("State is now " + x)
}
或
object Bar extends Foo {
type State = Int
override def updateState: Int => Unit = ???
}
取决于您选择的选项。
我有一个抽象方法
def updateState: (Any*) => Unit
我试图通过以下方式在 child class 中覆盖:
override def updateState = (sharedOptimizer: Vector[Double],
sharedMeanGradient: Vector[Double],
sharedHistoricalGradients: Array[Vector[Double]]) => {
()
}
我不明白为什么编译器returns我这个错误:
Error:(75, 81) type mismatch;
found : (Vector[Double], Vector[Double], Array[Vector[Double]]) => Unit
required: Any* => Unit
类型 Any*
不是应该表示 "any number of arguments of any type" 吗?
类型Any*
只是一个普通类型,就像Int
或List[String]
一样。
就像你不能覆盖一个方法一样
def foo(x: List[String]): Unit
来自
def foo(x: Int): Unit
你也可以不覆盖
def updateState: (Any*) => Unit
来自
def updateState:
(Vector[Double], Vector[Double], Array[Vector[Double]]) => Unit
因为 (Vec[D], Vec[D], Arr[Vec[D]])
不是 Any*
的超类型,即有很多东西可以作为 Any*
传递,而不是 (Vec[D], Vec[D], Arr[Vec[D]])
.
如果您不想立即对状态类型进行硬编码,请用它来参数化您的 class:
trait Foo[S] {
def updateState: S => Unit
}
或使其成为类型成员:
trait Foo {
type State
def updateState: State => Unit
}
然后你可以在 subclasses:
中覆盖它object Bar extends Foo[Int] {
override def updateState: Int => Unit =
x => println("State is now " + x)
}
或
object Bar extends Foo {
type State = Int
override def updateState: Int => Unit = ???
}
取决于您选择的选项。