简体   繁体   English

通过将 Unit 作为类型传递给泛型特征的可选方法参数

[英]Optional method argument by passing Unit as type to generic trait

Say I have a trait:说我有一个特点:

trait Foo[T] {
    val x: T => Any
}

Now I want to make it possible to omit the function argument, by making it a unit:现在我想通过将其设为一个单位来省略 function 参数:

class Bar extends Foo[Unit] {
  override val x = () => "Hello"
}

The above code does not compile ("x overrides nothing").上面的代码无法编译(“x 不会覆盖任何内容”)。

Is there a way to make this work in Scala?有没有办法在 Scala 中进行这项工作?

I think the misunderstanding here is that () is not a value of type Unit but instead represents an empty argument list.我认为这里的误解是()不是Unit类型的值,而是表示一个空参数列表。 So所以

() => "Hello"

is a unary function without argument.是没有参数的一元 function。 However, your trait expects a function that takes one argument of type Unit .但是,您的 trait 需要一个 function ,它接受一个Unit类型的参数。

If you remove the override , which isn't necessary here, you will get a compiler error, that will point you in that direction.如果你删除了这里不需要的override ,你会得到一个编译器错误,它将指向那个方向。 If you then replace the () with a wildcard _ or better yet (_: Unit) , your code will compile.如果您随后将()替换为通配符_或更好的(_: Unit) ,您的代码将编译。

trait Foo[T] {
    val x: T => Any
}

trait Bar extends Foo[Unit] {
  val x: Unit => Any = (_: Unit) => "Hello"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM