Read the whole series:
Part 1 – type inference <- you’re here
Part 2 – traits
Part 3 – case class/object (ADTs)
Part 4 – apply & unapply functions
Part 5 – implicits
It’s a new year, a new job, a new language (Scala) and runtime (JVM) to work with.
After a week of learning about my new surroundings at Space Ape Games and getting up to speed with Scala I have learnt a fair bit. In my own journey (aided by Twitter’s Scala School, Odersky’s Coursera course and Effective Scala) I found the target audience for a lot of online materials is Java developers, or developers who are new to functional programming.
As a proficient F# developer, a lot of the FP concepts translate quite easily to Scala (albeit with a different, more verbose syntax). However, Scala does have a lot of language features that do not exist in F# and many things (such as type inference) work slightly differently and can bite you in subtle ways if caught unaware of these differences.
So, for anyone coming into Scala from F#, I hope I can provide some useful info based on the things that I found interesting in my journey.
One of those things is how type inference differs in the two languages.
F# uses a Hindley-Milner type inference system similar to its ML brethren, but Scala’s type inference works slightly differently.
Take the following example for instance, this bit of code works just fine in F#.
but the same doesn’t work in Scala…
unless you explicitly specify the type parameter for toList.
Interestingly, if you rewrite the function in curried form then the Scala compiler is able to infer the type for toList.
but the order of parameters matters somehow..
which I eventually understood thanks to some helpful folks on Twitter.
Although less restrictive, this limitation of only being able to unify types from left to right also applies to F#.
For example, a simple example using the backward pipe (<|) is enough to cause the compiler to bark.
I hope this has been useful for you, over the next weeks or months I should be adding more posts to this series as I better familiarise myself with Scala, both in terms of language features as well as the toolchain/ecosystem around it.
See here for the rest of the series (as they become available).