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)

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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. ;)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.