Posts in the “scala” category

One example of how to avoid using `var` fields in Scala

As one note and example of how to avoid using var fields in Scala, I initially wrote this code:

var numDaysToProcess = 0

if (args.length != 0) {
    numDaysToProcess = args(0).toInt
}

After I looked at that code for a moment I realized that I could write it without a var like this instead:

val numDaysToProcess =
    if (args.length == 0) {
        0
    } else {
        args(0).toInt
    }

That’s a simple example of one situation where you can easily avoid using a var field in Scala. I’ll share more examples as they come up.

How to read Scala command line arguments

Scala command line FAQ: How do I read command line arguments (args) in a Scala shell script?

If your Scala shell script is very short, and you're not using an object or class declaration -- i.e., you have no main method -- you can access the script's command line arguments through the default args array, which is made available to you by Scala.

For instance, you can create a one-line Scala script named hello.scala like this:

How to determine if a Scala String contains a regular expression pattern

[toc]

Scala String FAQ: How can you determine whether a String contains a regular expression pattern in Scala? (Or, “How can I find the first match (or all matches) of a regex in a String?”)

Solution: findFirstIn, findAllIn

Create a Regex object by invoking the .r method on a String, and then use that pattern with findFirstIn when you’re looking for one match, and findAllIn when looking for all matches.

The Play Framework template comments syntax

When you want to create Play Framework template comments, use the @* ... *@ syntax. Here's a one-line comment:

@* COMMENT *@

Here's a multiline comment:

@*
 * Four score
 * and seven year ago
 * our fathers ...
 *@

(You can format that however you want.)

You can use comments as the first line of Play Framework templates (before the function declaration):

How to use Lift-JSON to parse JSON array data

If you ever need to parse JSON stock data from alphavantage.co using Scala, here’s a test class I just wrote that uses Lift-JSON.

The JSON data format

First, here’s the JSON I get back from them:

{
    "Meta Data": {
        "1. Information": "Batch Stock Market Quotes",
        "2. Notes": "IEX Real-Time Price provided for free by IEX (https://iextrading.com/developer/).",
        "3. Time Zone": "US/Eastern"
    },
    "Stock Quotes": [
        {
            "1. symbol": "MSFT",
            "2. price": "91.6000",
            "3. volume": "23511825",
            "4. timestamp": "2018-01-22 16:00:00"
        },
        {
            "1. symbol": "FB",
            "2. price": "186.4000",
            "3. volume": "20946922",
            "4. timestamp": "2018-01-22 16:41:06"
        },
        {
            "1. symbol": "AAPL",
            "2. price": "176.8900",
            "3. volume": "27027474",
            "4. timestamp": "2018-01-22 16:00:00"
        }
    ]
}

I get that array back when I access a URL like this:

  • https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=MSFT,FB,AAPL&apikey=demo

Parsing the JSON

Next, here’s how I parse that JSON using Scala and Lift-JSON:

import net.liftweb.json.DefaultFormats
import net.liftweb.json._
import scala.collection.mutable.ArrayBuffer

object Test2 extends App {

    val json = parse(SampleData.data)
    implicit val formats = DefaultFormats

    val elements = (json \\ "Stock Quotes").children

    val stocks = ArrayBuffer[Stock]()
    // keys are: "1. symbol", "2. price", "3. volume", "4. timestamp"
    // i expect 3 stocks, so ...
    for (i <- 0 until 3) {
        val e = elements(0)(i)
        // Map(1. symbol -> MSFT, 2. price -> 91.6000, 3. volume -> 23511825, 4. timestamp -> 2018-01-22...)
        val values = e.values.asInstanceOf[Map[String,String]]   //coercion
//        for ((k,v) <- values) printf("key: %s, value: %s\n", k, v)
//        println("")
        stocks += Stock(values("1. symbol"), values("2. price"))
    }

    stocks.foreach(println)

    case class Stock(symbol: String, price: String)


}

The output

The output of that code looks like this:

Stock(MSFT,91.6000)
Stock(FB,186.4000)
Stock(AAPL,176.8900)

Discussion

The source code is ugly I write now because I just got it working, but I thought I’d share it here in case you need to parse some JSON data that’s in an array format like this. I’m more used to working with JSON that represents objects — see my other Scala/JSON examples — but this data is more of an “array of arrays” format, so this approach is different than my previous examples.

My build.sbt file

As a final note, my build.sbt file looks like this:

name := "StockQuotes2018"

version := "1.0"

scalaVersion := "2.12.4"

libraryDependencies ++= Seq(
    "net.liftweb" %% "lift-json" % "3.1.1"
)

scalacOptions += "-deprecation"

Play Framework: Anorm SQL query syntax and examples

[toc]

In general the online Play Framework documentation is excellent, but one area where I needed more help was in seeing more examples of the Anorm syntax. To that end, here are some Anorm query examples, taken from a Play Framework application I worked on recently. But first, a little background about Anorm.

Is Scala DICEE?

If you’ve never heard of the term DICEE, it was coined by Guy Kawasaki. Mr. Kawasaki was a developer evangelist for the original Macintosh team in the 1980s, and used the term in at least one subsequent book to refer to great products.

“DICEE” is an acronym that stands for Deep, Indulgent, Complete, Elegant, and Emotive:

Scala best practice: How to use the Option/Some/None pattern

[toc]

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 20.6, “Scala best practice: How to use the Option/Some/None pattern.”

Problem

For a variety of reasons, including removing null values from your Scala code, you want to use what I call the Option/Some/None pattern. Or, if you’re interested in a problem (exception) that occurred while processing code, you may want to return Try/Success/Failure from a method instead of Option/Some/None.

Functional error handling in Scala

Because functional programming is like algebra, there are no null values or exceptions. But of course you can still have exceptions when you try to access servers that are down or files that are missing, so what can you do? This lesson demonstrates the techniques of functional error handling in Scala.