Search code examples
scalasingle-abstract-method

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?


Solution

  • 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 (i.e. if it doesn't have a parameter list) because SAM-conversion only applies if the single method has exactly one parameter list.