Reputation: 1802
Let's say I have:
val sayHello: Int => Unit = {_ => println("hello")}
val sayHi: Int => Unit = {_ => println("hi")}
And a function such as foo
:
val foo: Int => Unit = {
sayHi
}
foo(123) //= prints hi
Is there a way of writing this:
val bar: Int => Unit = {
i =>
sayHello(i)
sayHi(i)
}
without the i
parameter? so that I can run both sayHi
and sayHello
?
I mistakenly had in my code the following:
val foo: Int => String = {
sayHello
sayHi
}
but this only uses the last expression and sayHello
is not run.
In general, if this functions were to return anything other than Unit
, let's say what is the idomatic way of bunlding these functions so that
val Hello: Int => String = {_ => "hello"}
val Hi: Int => String = {_ => "hi"}
what is the most idomatic implementation of the function bar:
def bar: Int => Seq[String]
such that:
bar(123) // returns List("hello","hi")
Upvotes: 1
Views: 62
Reputation: 37832
How about:
def bar: Int => Seq[String] = i => Seq(Hello, Hi).map(_(i))
For the Unit
-returning functions case, you can replace the map
with foreach
:
def bar: Int => Unit = i => Seq(Hello, Hi).foreach(_(i))
Upvotes: 1