MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala Best Practices

Examples

Keep it simple


Do not overcomplicate simple tasks. Most of the time you will need only:

• algebraic datatypes

• structural recursion

• monad-like api (map, flatMap, fold)


There is plenty of complicated stuff in Scala, such as:

• Cake pattern or Reader Monad for Dependency Injection.

• Passing arbitrary values as implicit arguments.


These things are not clear for newcomers: avoid using them before you understand them. Using advanced concepts without a real need obfuscates the code, making it less maintainable.

Don't pack too much in one expression.


• Find meaningful names for computation units.

• Use for comprehensions or map to combine computations together.


Let's say you have something like this:

if (userAuthorized.nonEmtpy) {
 makeRequest().map {
 case Success(respone) =>
 someProcessing(..)
 if (resendToUser) {
 sendToUser(...)
 }
 ...
 }
}

If all your functions return Either or another Validation-like type, you can write:

for {
 user <- authorizeUser
 response <- requestToThirdParty(user)
 _ <- someProcessing(...)
} {
 sendToUser
}


Conclusion

In this page (written and validated by ) you learned about Scala Best Practices . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Case Classes.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.