The most variation in your question in converting methods to function values. There are a few different ways to convert a method into a function value. Let’s say you have the following method:
def showInt(i: Int): Unit = println(s"the value is $i")
you can convert that in to a function value by following the name with _
:
val shower = showInt _
you can also use partial application syntax, and leave the only parameter blank:
val shower = showInt(_)
you could also use a function literal
val shower = (i: Int) => showInt(i)
If the expected type is fully known and doesn’t need to be inferred, you have some additional options and shorthands. The shortest is that you can just give the name of the method
val shower: Int => Unit = showInt
If there is an expected type and you use a literal, you can also leave out the parameter type since it’s already known from the expected type:
val shower: Int => Unit = (i: Int) => showInt(i)
//instead of this, you already know that i: Int
//so you can write it shorter as follows
val shower: Int => Unit = i => showInt(i)
and you can also define it in cases:
val shower: Int => Unit = { case i => showInt(i)}
the i
in that last one can be any pattern, so you can do things like this:
val shower: Int => Unit = {
case 1 => println("one")
case n if n < 5 => println("a few")
case n => println("more than a few")
}
Then you can pass shower
to foreach
–
List(1, 2, 3).foreach(shower)
or in infix notation
List(1, 2, 3) foreach shower
Like I said earlier, you can also put as many extra braces and brackets around an expression as you want, and it won’t change a thing: 1 == (1) == {1} == {({{(1)}})}
So the following is also legal:
List(1, 2, 3) foreach {({shower})}
From there, you can do all variations you want. You can always do the full literal syntax, but you may prefer a less verbose alternative if it isn’t needed.