Search code examples
scalapartialfunction

Implementing a scala method using a partial function


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)


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