Question

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)

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top