1

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?

Maths noob
  • 1,684
  • 20
  • 42

1 Answers1

2

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.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • thanks. Sadly `toString` which initiated this problem is an example of `def foo: String` so it looks like I cannot use SAMs with it. – Maths noob Sep 21 '18 at 14:22
  • @Mathsnoob `toString` in your example is in the implementation, not the method being defined, that's not a problem. And for those `def foo: String` cases, you don't get SAM-conversion for free, but an equivalent can be easily added. – Alexey Romanov Sep 22 '18 at 06:30