简体   繁体   中英

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:

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

The above code does not compile ("x overrides nothing").

Is there a way to make this work in Scala?

I think the misunderstanding here is that () is not a value of type Unit but instead represents an empty argument list. So

() => "Hello"

is a unary function without argument. However, your trait expects a function that takes one argument of type Unit .

If you remove the override , which isn't necessary here, you will get a compiler error, that will point you in that direction. If you then replace the () with a wildcard _ or better yet (_: Unit) , your code will compile.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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