1

For example, in previous question: Scala coding styles and conventions?

Someone complains "If the method grows it becomes very painful to read the code" ..

and Dr. Martin Odersky replied ".. The functional programing style is to have many small methods..."

So does it mean when you are using Scala, you should write in FP style as much as possible and don't take Scala as a Java replacement.

Community
  • 1
  • 1
Ryan
  • 10,041
  • 27
  • 91
  • 156

3 Answers3

3

The beauty of Scala is that it can be different things to different people. Writing in a functional way is encouraged. However, you can write Scala in an imperative style also.

Even when writing in an imperative style, you are encouraged to write small methods. That makes code easier to read and thus maintain.

Zack Marrapese
  • 12,072
  • 9
  • 51
  • 69
3

Just to give you a small example, why functional style is encouraged, imagine you have 2 lists of integers of not guaranteed same size and you have to create a new list of integers with all the sums up to the length of the shorter list. In an imperative style, you would do something like this:

val list1 = List(1,2,3,4,5)
val list2 = List(1,2,3,4,5,6,7)

// imperative way
val newList = collection.mutable.ListBuffer[Int]()

val length = math.min(list1.size, list2.size)

for(i <- 0 until length) {
  newList += list1(i) + list2(i)
}

// functional way
list1.zip(list2).map { case (x,y) => x+y }

See, the second example is much smaller and much more focused on "what" to do and not "how" to do it. Everyone has to start at some point and at first you can write normal imperative code, but sooner or later you will adopt more and more functional paradigms, just because they make your code a lot better and safer.

drexin
  • 24,225
  • 4
  • 67
  • 81
0

What I love about Scala is that it's a multi-paradigm language. You can write your code in whatever is the best way for the problem at hand.

I strongly suspect that, over time, you'll move towards a more functional style in some of your code. But not necessarily all (there really are some problems for which an imperative approach describes the problem more succinctly).

There are certainly some people who will cast this kind of thing in terms of "right" and "wrong", but I suspect that they're missing the point. If you want to write purely functional code, use a purely functional language.

Paul Butcher
  • 10,722
  • 3
  • 40
  • 44