1

I have a class, as follows:

trait Foo {
  def greet(name: String) : String
}

trait Bar {
  def hello(name: String) = s"Hello ${name}!"
}

class Greeter extends Foo with Bar {
  def greet(name: String) = hello(name)
}

I'm curious if it is possible to implement greet using a partial application of the hello method? Something like:

class Greeter extends Foo with Bar {
  def greet = hello
}

(Obviously this doesn't work)

Chris Leishman
  • 1,777
  • 13
  • 19

2 Answers2

2

In Scala you often have to explicitly state when you want to apply a method only partially. This is done by writing an underscore behind the method name (but do not forget a space before that). In your case it would work as follows:

def greet = hello _

EDIT: After what @Richard Sitze observed, you could amend the situation by slightly changing the definition of Foo as follows:

trait Foo {
  def greet : String => String
}

Whether this is appropriate of course depends on your specific setup.

chris
  • 4,988
  • 20
  • 36
2

While you can certainly implement greet, as noted by @chris, that code snippet overloads Foo.greet(name:String); it does not override it:

class Greeter extends Foo with Bar {
    def greet = hello _
}

<console>:9: error: class Greeter needs to be abstract, since method
       greet in trait Foo of type (name: String)String is not defined
       class Greeter extends Foo with Bar { def greet = hello _ }

While the following does compile:

class Greeter extends Foo with Bar {
    def greet(name: String) = hello(name)
    def greet = hello  _
}

As an aside, you can also define greet with an explicit type decl, without the trailing underscore:

def greet: String=> String = hello
Richard Sitze
  • 8,262
  • 3
  • 36
  • 48
  • 1
    So, in summary, it's not possible to do this unless the super class had already defined the method as String => String, rather than (name: String)String. Interesting that `def greet(name: String) = hello(name)` and `def greet = hello _` are not the same, despite having the same name and effective type of String => String, and that one can define both in the same class. Haskell 1, Scala 0. ;) – Chris Leishman May 05 '13 at 18:48