or learn more

Comparing Lines of Code: Scala and Clojure (FUD version)

Jan 4, 2010

A completely tongue in cheek comparison between Scala and Clojure, implementing the famous closure test.

Scala Version1

type Supercalifragilisticexpialidocious = java.lang.Integer

implicit def Supercalifragilisticexpialidocious2Int(tehThingToConvert:Supercalifragilisticexpialidocious) = {

trait ClosureTestMixin {
  def makeAdder(tehAdditionValue:Supercalifragilisticexpialidocious):Function1[Int,Int]

class AdderMaker extends ClosureTestMixin {
  def apply(tehAdditionValue:Supercalifragilisticexpialidocious):Function1[Int,Int] = {
    new Function1[Int,Int] {
      def apply(tehOtherAdditionValue:Int):Int = {
        return tehAdditionValue.$plus(tehOtherAdditionValue.asInstanceOf[Supercalifragilisticexpialidocious])

  def makeAdder(tehAdditionValue:Supercalifragilisticexpialidocious):Function1[Int,Int] = {
    return this.apply(tehAdditionValue)

val tehAdderMakerInstance = new AdderMaker()

val tehAdderPlus10 = tehAdderMakerInstance.makeAdder(10)

//=> 19

Clojure Version

(defn mk-adder [x] #(+ % x))
(def add10 (mk-adder 10))
(add10 9)
;=> 19

To perform this simple exercise the Scala version requires2 29 lines and ~960 characters! The Clojure version on the other hand requires only 3 lines and 64 characters.

Need I say more?3


  1. Any suggestions for making this longer? 

  2. Nope, not at all. 

  3. Just in case there was any ambiguity — the Scala version was intentionally obfuscated for chuckles. For a much more eloquent rebutal of flawed LOC comparisions read Stephan Schmidt’s latest post on the subject. 

7 Comments, Comment or Ping

  1. You should replace the “+” in the Scala code with “$plus”, a beginners mistake, but hey, we’re all learning :) Also, consider making it a monad…

  2. @Gabriel Done! I will play around later with making the Scala version more monadic. Thanks for the tips!

  3. Josh Cough

    :) can you do it in reverse too?

  4. I can’t believe you wasted so many lines in your Clojure version.

    (((fn mk-adder [x] #(+ % x)) 10) 9)

    only 35 characters and does roughly the same thing. :)

  5. @Josh Cough

    That will be the next post. :-)

  6. Leo

    I am also new to Scala. Not quite sure about the closure test Why we could not use below in Scala? I think it’s quite similar to the 29 lines code

    def addPlus10: Function1[Int, Int] = 10 + _ addPlus10(9)

  7. Edward

    Just started Scala with Martin Odersky’s Coursera course and Week 2 covered higher order functions.

    I think this should do it, seems pretty easy actually.

    def makeAdder(incr: Int): Int=>Int = x => x + incr def plus10 = makeAdder(10) plus10(9)

    Yes I realise this post is an old joke, but I wanted to apply what I had learned.

Reply to “Comparing Lines of Code: Scala and Clojure (FUD version)”