Stuart Harrell
Stuart Harrell

Reputation: 127

Why can case class be passed as a function

Case classes can be passed as functions, how could I make a regular class be passed as a function in the same way?

case class Fraction(val num: Int, val den: Int)

object Run extends App {
    def doFraction(in: (Int, Int) => Fraction) {}

    doFraction(Fraction)
}   

The above code works, how could I modify the code below to get the same effect?

class Fraction(val num: Int, val den: Int) {
    /* what can I put here or in companion object to make this compile? */
}

object Fraction {
    /* ... */
}

object Run extends App {
    def doFraction(in: (Int, Int) => Fraction) {}

    doFraction(Fraction)
}   

Upvotes: 1

Views: 105

Answers (2)

Vatel
Vatel

Reputation: 106

In any case you have to implement the corresponding apply method (apply(Int, Int): Fraction in your case). If you do not want inheritance in object Fraction (as Lex said), the following code will work too:

doFraction(Fraction.apply _)

Fraction.apply _ converts you Fraction.apply method to a function of type (Int, Int) => Fraction

As for case classes, you may look into generated bytecode and see that the companion object's generated class will already extend (Int, Int) => Fraction. There still some nuances - look at this for details: https://groups.google.com/forum/#!msg/scala-user/ZhSDMJgwghc/DZpbzvVYHXIJ

Upvotes: 0

Lex
Lex

Reputation: 1184

Your companion object needs to extend Function trait and have the apply() method defined:

// object Fraction extends Function2[Int, Int, Fraction]
object Fraction extends ((Int, Int) => Fraction) {
  def apply(num: Int, den: Int) = new Fraction(num, den)
}

Upvotes: 8

Related Questions