Posts in the “scala” category

How to read Atom and RSS feeds using Scala

In case you ever need to read an Atom or RSS feed using Scala, this example code shows how to use the Java ROME library in your Scala code:

import java.net.URL
import com.rometools.rome.feed.synd.{SyndFeed}
import com.rometools.rome.io.SyndFeedInput
import com.rometools.rome.io.XmlReader
import scala.collection.JavaConverters._

object AtomAndRssReader extends App {

    // NOTE: code can throw exceptions
    val feedUrl = new URL("https://www.npr.org/rss/rss.php?id=100")
    val input = new SyndFeedInput
    val feed: SyndFeed = input.build(new XmlReader(feedUrl))
    //println(feed)


    // `feed.getEntries` has type `java.util.List[SyndEntry]`
    val entries = asScalaBuffer(feed.getEntries).toVector

    for (entry <- entries) {
        println("Title: " + entry.getTitle)
        println("URI:   " + entry.getUri)
        println("Date:  " + entry.getUpdatedDate)

        // java.util.List[SyndLink]
        val links = asScalaBuffer(entry.getLinks).toVector
        for (link <- links) {
            println("Link: " + link.getHref)
        }

        val contents = asScalaBuffer(entry.getContents).toVector
        for (content <- contents) {
            println("Content: " + content.getValue)
        }

        val categories = asScalaBuffer(entry.getCategories).toVector
        for (category <- categories) {
            println("Category: " + category.getName)
        }

        println("")

    }

}

A few notes:

  • The code uses Scala’s JavaConverters class to convert the java.util.List instances into something more usable
  • You need to add the Rome dependency to your build.sbt file ("com.rometools" % "rome" % "1.8.1")
  • Of course the ROME library does all the heavy lifting; I just show how to use it in Scala, in particular with the JavaConverters class

The output

Here’s an abridged version of what the output from this code looks like today:

Title: Episode 820: P Is For Phosphorus 
URI:   https://www.npr.org/sections/money/2018/01/26/581156723/episode-820-p-is-for-phosphorus?utm_medium=RSS&utm_campaign=storiesfromnpr
Date:  null
Content: <img src='https://media.npr.org/assets/img/2018/01/26/gettyimages-168997967_wide-3e6007bd49a94a161553cba256335550e12cfb37.jpg?s=600' /><p>Phosphate is a crucial element, for farming, and for life ...

Title: The 10 Events You Need To Know To Understand The Almost-Firing Of Robert Mueller
URI:   https://www.npr.org/2018/01/26/580964814/the-10-events-you-need-to-know-to-understand-the-almost-firing-of-robert-mueller?utm_medium=RSS&utm_campaign=storiesfromnpr
Date:  null
Content: <img src='https://media.npr.org/assets/img/2018/01/26/mueller-2013_wide-ea9e74cdb89431d2e2ebd476acc67cce3cd67167.jpg?s=600' /><p>Everything about this story revolves around obstruction of justice ...

Note that the Date output is null. I haven’t looked into that yet — it’s not important for my needs — but as you can see, the rest of the output looks just fine, and the code works as intended.

How to set the classpath in a Scala script (Scala shell script)

Scala script FAQ: How do I set the CLASSPATH in a Scala shell script?

If you need to set the CLASSPATH when executing a Scala script, use the exec command as shown in the following example:

#!/bin/sh
exec scala -classpath "lib/htmlcleaner-2.2.jar:lib/scalaemail_2.9.1-1.0.jar:lib/stockutils_2.9.1-1.0.jar" "$0" "$@"
!#

As you can see from that code, I'm adding three jar files to my classpath at the beginning of my Scala shell script.

Fun with Scala functions (andThen and compose)

Here’s a little fun with Scala functions, including the use of andThen and compose:

scala> val add1 = (i: Int) => i + 1
add1: Int => Int = <function1>

scala> val double = (i: Int) => i * 2
double: Int => Int = <function1>

scala> val addThenDouble = add1 andThen double
addThenDouble: Int => Int = <function1>

scala> addThenDouble(1)
res0: Int = 4

scala> val doubleThenAdd = add1 compose double
doubleThenAdd: Int => Int = <function1>

scala> doubleThenAdd(1)
res1: Int = 3

(Inspired by the book, Functional and Reactive Domain Modeling, and my own book, Learning Functional Programming in Scala.)

An RSS Reader written with Scala and JavaFX (the beginning)

I just started writing an RSS Reader application using JavaFX and Scala, and I thought I’d post the initial code here. This code shows several advanced Scala techniques that Scala developers might need to use when writing Scala code to interact with Java, and in this case, JavaFX.

The original Scala Cookbook Preface

The Preface was the last chapter I wrote in the Scala Cookbook. Initially I didn’t plan to write a Preface for the book, but I was more or less told by my editor that it was mandatory. So I waited until I finished the rest of the book before starting on it. To me that made sense; I couldn’t write a decent Preface without knowing the final contents of the book.

How to use Scala enums (Enumeration)

Problem: You want to use an enumeration (a set of named values that act as constants) in your Scala application.

Solution

Extend the scala.Enumeration class to create your enumeration:

package com.acme.app {

    object Margin extends Enumeration {
        type Margin = Value
        val TOP, BOTTOM, LEFT, RIGHT = Value
    }

}

Then import the enumeration to use it in your application:

How to merge Scala Lists

Scala List FAQ: How do I merge a List in Scala?

NOTE: I wrote the solutions shown below a long time ago, and they are not optimal. I'll update this article when I have more time. The best approach is to prepend one List to the beginning of another List with the :: method.

There are at least three ways to merge/concatenate Scala List instances, as shown in the examples below.

Third proof of Functional Programming, Simplified

I like the cover so much, I’m now up to three copies of Functional Programming, Simplified.

A little more seriously, I’ll be reviewing the third proof tonight. If all goes well, the book will be available on Amazon.com this weekend.