Struggle against habits formed by Java when migrating to Scala

后端 未结 7 762
星月不相逢
星月不相逢 2021-02-01 08:48

What are the most common mistakes that Java developers make when migrating to Scala?

By mistakes I mean writing a code that does not conform to Scala spirit, for example

7条回答
  •  被撕碎了的回忆
    2021-02-01 09:31

    Using if statements. You can usually refactor the code to use if-expressions or by using filter.

    Using too many vars instead of vals.

    Instead of loops, like others have said, use the list comprehension functions like map, filter, foldLeft, etc. If there isn't one available that you need (look carefully there should be something you can use), use tail recursion.

    Instead of setters, I keep the spirit of functional programming and have my objects immutable. So instead I do something like this where I return a new object:

    class MyClass(val x: Int) {
        def setX(newx: Int) = new MyClass(newx)
    }
    

    I try to work with lists as much as possible. Also, to generate lists, instead of using a loop, use the for/yield expressions.

提交回复
热议问题