Reputation: 1028
Scala: How to make multiple methods and apply them one by one?
I have a list: List("1", "2", "3")
and a method:
def concat(str: String)(tail: String): String = str + tail
My aim is to make three (imaginary) methods:
concat(str: String)("1")
concat(str: String)("2")
concat(str: String)("3")
and then apply these three methods one by one to a test string "abc":
then I'll have the result: "abc123"
What is the functional way to do this? Any hints are appreciated.
Upvotes: 1
Views: 112
Reputation: 22439
You don't need 3 different methods. Just use fold
to traverse your list and apply your concat
method successively:
val list = List("1", "2", "3")
def concat(str: String)(tail: String): String = str + tail
list.fold( "abc" )( concat(_)(_) )
// res1: String = abc123
Note that fold( "abc" )( concat(_)(_) )
is just a shortcut for:
fold( "abc" )( (acc, x) => concat(acc)(x) )
In case you aren't familiar with fold
, here's the API doc
Upvotes: 4