简体   繁体   中英

Scala: single abstract methods without a parameter

With SAM types, we can have:

trait Sam {
  def foo(i: Int): String
}

val sam : Sam = _.toString

What if my abstract method doesn't have a parameter?

You can use a lambda with an empty argument list like this:

trait Sam {
  def foo(): String
}

val sam : Sam = () => "hello"

You can not use _ notation because there's no way to define a zero-argument function with _ .

This won't work if foo is defined as def foo: String instead (ie if it doesn't have a parameter list) because SAM-conversion only applies if the single method has exactly one parameter list.

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