From F# to Scala — type inference

Read the whole series:

Part 1 — type infer­ence <- you’re here

Part 2 — traits

Part 3 — case class/object (ADTs)

Part 4 — apply & unap­ply func­tions

Part 5 — implic­its

It’s a new year, a new job, a new lan­guage (Scala) and run­time (JVM) to work with.

After a week of learn­ing about my new sur­round­ings at Space Ape Games and get­ting up to speed with Scala I have learnt a fair bit. In my own jour­ney (aid­ed by Twitter’s Scala School, Odersky’s Cours­era course and Effec­tive Scala) I found the tar­get audi­ence for a lot of online mate­ri­als is Java devel­op­ers, or devel­op­ers who are new to func­tion­al pro­gram­ming.

As a pro­fi­cient F# devel­op­er, a lot of the FP con­cepts trans­late quite eas­i­ly to Scala (albeit with a dif­fer­ent, more ver­bose syn­tax). How­ev­er, Scala does have a lot of lan­guage fea­tures that do not exist in F# and many things (such as type infer­ence) work slight­ly dif­fer­ent­ly and can bite you in sub­tle ways if caught unaware of these dif­fer­ences.

So, for any­one com­ing into Scala from F#, I hope I can pro­vide some use­ful info based on the things that I found inter­est­ing in my jour­ney.

One of those things is how type infer­ence dif­fers in the two lan­guages.


F# uses a Hind­ley-Mil­ner type infer­ence sys­tem sim­i­lar to its ML brethren, but Scala’s type infer­ence works slight­ly dif­fer­ent­ly.

Take the fol­low­ing exam­ple for instance, this bit of code works just fine in F#.

but the same doesn’t work in Scala…

unless you explic­it­ly spec­i­fy the type para­me­ter for toList.

Inter­est­ing­ly, if you rewrite the func­tion in cur­ried form then the Scala com­pil­er is able to infer the type for toList.

but the order of para­me­ters mat­ters some­how..

which I even­tu­al­ly under­stood thanks to some help­ful folks on Twit­ter.


Although less restric­tive, this lim­i­ta­tion of only being able to uni­fy types from left to right also applies to F#.

For exam­ple, a sim­ple exam­ple using the back­ward pipe (<|) is enough to cause the com­pil­er to bark.

I hope this has been use­ful for you, over the next weeks or months I should be adding more posts to this series as I bet­ter famil­iarise myself with Scala, both in terms of lan­guage fea­tures as well as the toolchain/ecosystem around it.

See here for the rest of the series (as they become avail­able).

Liked this post? Why not support me on Patreon and help me get rid of the ads!