“Scalalified” code vs functional style code

One of the my colleagues said the following about scala (and I completely share his opinion):

It takes significantly more time to write proper code in Scala then in Java, but when it is done right then it looks so cool and precise!”

One comment about it that it has nothing to do with Java. It can be any imperative language. In this post I will share some examples from real code base, which implemented in Scala. And how it could be implemented in a more functional style. I will update the examples as I encounter them.

So the first one is here. Lets say, you implement an utility which accepts input parameters. Below you can find example how you can parse two input parameters. For example, your utility expects host and port.

val host = 
    if (args.isEmpty)
      "localhost"
    else
      args(0)


val port =
    if (args.isEmpty || args.length <= 1)
      8080
    else
      args(1).toInt

Note that the code above uses some nice scala features, like returned value from an “if” statement or type detection (host is String, while, port is Int). But it is implemented in a purely imperative style. That is what I call “scalalified” code.

Is it possible to implement it more elegant in Scala? I am sure it is. For example like this:

  val defaultPort = 8080
  val (host, port) = args match {
      case Array(host, port, _*) => (host, port)
      case Array(host, _*) => (host, defaultPort)
      case _ => ("localhost", defaultPort)
    }

Indeed, pattern matching to the rescue…

To be continued ….

Leave a comment

Leave a comment