Passing Functions in Scala, or how Scala Embarrasses OO languages and Their Pretentious Strategy Pattern

Being able to pass functions is underappreciated. It’s hard to believe that some languages don’t have the ability. For some reason, when a language doesn’t support passing functions, people figure out a way. That’s got to be how the “Strategy” pattern emerged in OO languages. And since it was now considered some kind of fancy design pattern, it seemed more amazing.

Well, it’s not amazing. Really it’s just pretentious. It’s not special. It’s how things should be done sometimes. But enough with my chatter. Here’s how you do it in Scala. It’s easy. It’s routine. It’s boring. And that’s the way it should be.

  1. Figure out what you’re doing. For this example, let’s pretend we’re giving super powers to superheroes. It’s way more interesting than those math examples where all we’re doing is adding, subtracting, or multiplying two numbers together.
  2. Define a function that takes a function argument. Function arguments look like this:
    //1. function type that describes a function which takes a String, and returns an Int, like String.length
    String => Int 
    //2. function type that describes a function that takes two parameters, both Ints, and returns an Int, like sum
    (Int, Int) => Int 
    //3. function type that describes a function that takes MyType and returns YourType
    MyType => YourType
    //4. function type that describes a function which takes a String, an Int, and a MyType, and returns a "Unit" (like Java's "void" methods)
    (String, Int, MyType) => Unit

    Hopefully you can tell what’s going on here. Every function type starts with a list of parameter types which match to the expected functions argument list, is followed by “=>”, and finally ends with the return type.

    We’re going to define a function that has a superpower function argument, and uses the superpower to get free from a trap.

    def getFreeFromATrap(doSuperPower: String => Unit, trap: String) = {
        println(s"Oh no I'm in a ${trap}.")
        println(s"I will break free!")
  3. Now we can make all kinds of superpower functions.
    def flyOut(trap: String) = println(s"I fly out of the ${trap} and into the sky!")
    def superStrength(trap: String) = println(s"With my super strength, I can break the ${trap} and escape!")
    def laserVision(trap: String) = println(s"My laser vision destroys the ${trap} and I escape!")
    def invisibility(trap: String) = println(s"Using invisibility I evade the ${trap}!")
  4. And finally, we pass them in:
    getFreeFromATrap(flyOut, "quick sand")
    getFreeFromATrap(superStrength, "iron bars")
    getFreeFromATrap(laserVision, "collapsed tunnel")
    getFreeFromATrap(invisibility, "armed guards")
  5. See? Super easy.

    Here's all the code on Github Gists. You have to run it to find out what it says!

Leave a Reply

Your email address will not be published. Required fields are marked *