1

Is there such function concatenation in scala?

I remember in Haskell dot "." can concat two function.

E.g. I want to achieve

def f1(a:String) = a.toInt

def f2(a:Int) = a + 1

def f3 = f1 . f2
f3("123")
worldterminator
  • 2,968
  • 6
  • 33
  • 52
  • FYI, you have to write it backwards in Haskell: `f2 . f1`. – Karl Bielefeldt Feb 17 '17 at 11:03
  • Scala has function composition, but what you have there aren't functions, they are methods. You have to convert them to functions first. – Jörg W Mittag Feb 19 '17 at 02:25
  • @JörgWMittag I don't quite understand. What's the difference between functions and methods? Could you give me an example? – worldterminator Feb 19 '17 at 04:05
  • 1
    Methods have a name, functions don't. Methods can be Generic, functions can't. Methods can have multiple parameter lists (or none), functions can't, they always have exactly one parameter list. Methods can have optional parameters with default arguments, functions can't. Methods can have repeated parameters, functions can't. Methods can have an implicit parameter list, functions can't. So, if there is all those things methods can do that functions can't do, why do we even have functions at all? Well, there is one crucial difference: methods are members of objects, but not objects themselves … – Jörg W Mittag Feb 19 '17 at 10:10
  • 1
    … but functions *are* objects. And in an object-oriented language like Scala, that is *very* important! Because in an OO language, *everything* you do is done using objects. You call methods on objects and pass objects as arguments, returning objects as results. You store objects in variables. You can only "do stuff" with objects. For example, composing functions would be done by calling a method on a function and passing another function as an argument; and for that, the functions need to be objects. [This question](http://stackoverflow.com/a/42325151/2988) on function composition was just … – Jörg W Mittag Feb 19 '17 at 10:13
  • 1
    … asked and the answer also brushed on the difference between functions and methods in Scala. [This question](http://stackoverflow.com/q/2529184/2988) goes into much more detail. – Jörg W Mittag Feb 19 '17 at 10:14
  • @JörgWMittag thanks. Never went so deep. – worldterminator Feb 20 '17 at 10:11

1 Answers1

6

In Scala, you can use andThen to do this, like:

val f3 = f1 _ andThen f2 _
f3("123")

and Scala also has another method compose to combine function, compose likes the andThen function, but it call second function firstly and call the first function, like(f1(f2(_))`).

Reference:

http://www.scala-lang.org/api/rc2/scala/Function1.html

chengpohi
  • 14,064
  • 1
  • 24
  • 42