1

I have a Trait and its implementation, within which I want to reuse an existing function in a concise way. Here is the example:

object Util {
  def foo(a: Int, b:Int): Int = {// some implementation}
}
trait Animal {
  def eat(a: Int, b: Int): Int
}
object Dog extends Animal {
  import Util._
  def eat(a: Int, b:Int): Int = foo(a, b)
  /* Is this any concise way for the above? 
   * For example, I am looking for something 
   * like this to work:
   */
  // def eat = foo
  // def eat = foo(_, _)
  // val eat = foo(_, _)
}

2 Answers 2

1

If you simply wanted eat to be the same as foo, you could list the method foo into a function, and assign it to eat.

def foo(a: Int, b: Int): Int = ???
val eat = foo _

But it is not possible to use this approach when implementing a method from a trait like Animal. You must explicitly define the parameters of eat in Dog, which leaves you with:

def eat(a: Int, b: Int): Int = ???

I can't think of anything more concise and clear than foo(a, b).

Sign up to request clarification or add additional context in comments.

Comments

1

You can use eta-expansion as so:

val eat = foo _
val eat = foo(_, _) //equivalent

You can read more about eta-expansion on this blog post. This way, eat will have type (Int, Int) => Int. You can also do:

val eat = (foo _).curried

To get make eat have type Int => (Int => Int). You can read more about curried here.

You should note, too, that your use of the phrase "partial function" isn't how it is usually used. Partial functions in Scala (and generally) are functions that aren't necessarily defined on the entire domain. For example, in Scala:

val foo: PartialFunction[Int, String]  = { case 1 => "hello"; case 2 => "world" }
foo(1) //"hello"
foo.isDefinedAt(3) //false
foo(3) // exception

You can read more about partial functions in the docs here.

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.