Duck typing in functional programming languages and how to make you code more DRY using Scala
I know people started to hate compiled languages because of the restrictions a lot of them bring with them. Some developers felt like it gives me more pain than benefits. I am slower and less efficient.
Strongly typed languages have their benefits but devs -especially devs coming from the front-end world- always favored dynamic languages because of the freedom and weak typing they offer.
But it does not have to be always like that.
One of this wanted functionality is called duck typing.
This means that if two entities look alike, behave or act the same, I can treat them indifferently. If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.
Strong typed languages like Java do not have a straightforward way to achieve this feature -you may use reflection though but it adds lines of code- because you have to define a relationship between the structures themselves; you use classes and you would define a common interface. This has to be done at compilation time.
The issue with this approach is that sometimes you get code that you do not own or did not write. One class may have a method quark() and one of your own class also has a method quark(). Then it is difficult to deal with such classes.
Weak typed languages -often found in dynamic languages- do not enforce any classes relationships like inheritance, instead they focus on the behavior more than on the structure. It is checked at runtime.
Functional languages bring benefits of both world together. One feature which was missing in a language as Java is the possibility to treat functions a first class citizens meaning being able to pass them to other functions -the reference , not the result of the function/method computation- This aspect has for long being present in dynamic/scripting languages through functions and closures, yet it is not limited to them; Scala is a compiled strong typed language based on the JVM. It is mainly functional.
##First simple example: the Quacker
###Java example Test.java
###Javascript example:
###Scala example:
##DRY code: error handling
I lot of times when seeing people writing code in Java, I saw code duplication like this:
###Java:
By using a functional language it is very to easy to improve this code: Here the error handling is written only once.
###Scala: