@jducoeur and @LannyRipple, I thought I more or less understood after reading your responses. Then I looked back again at Scala/Chiusano (the red book), and it seems to contradict what I though I understood.
On page 21 and 22 of the red book, the authors define an object MyModule
with methods abs
and factorial
, then they later use the method names as function objects, which I wasn’t able to do in my original post. thunk::removes
Why can I use abs
(likeways factorial
) to mean the corresponding function object, in the call to formatResult
, but not in my original code in the call to ::
?
object MyModule {
def abs(n: Int): Int =
if (n < 0) -n
else n
def factorial(n: Int): Int = {
@annotation.tailrec
def go(n: Int, acc: Int): Int =
if (n <= 0) acc
else go(n-1, n*acc)
go(n, 1)
}
}
and later
object FormatAbsAndFactorial {
import MyModule._
// Now we can use our general `formatResult` function
// with both `abs` and `factorial`
def main(args: Array[String]): Unit = {
println(formatResult("absolute value", -42, abs))
println(formatResult("factorial", 7, factorial))
}
}