Posts in the “scala” category

How to append when writing to a text file in a Java or Scala application

As a quick Scala/Java tip, to append to a file when writing to a text file in a Scala or Java application, create your FileWriter with the append flag set to true, like this:

val bw = new BufferedWriter(new FileWriter(new File("/tmp/file.out"), true))  // <-- 'true'
bw.write("Hello, world\n")
bw.close

FileWriter takes two arguments, so that code might be easier to read when it’s formatted like this:

val bw = new BufferedWriter(
    new FileWriter(
        new File("/tmp/file.out"),
        true
    )
)
bw.write("Hello, world\n")
bw.close


Note: Appending to a text file with Scala 3

As a quick update, a great thing about Scala 3 is that you can get rid of all those new keywords, so the first part of that last example looks like this in Scala 3:

val bw = BufferedWriter(
    FileWriter(
        File("/tmp/file.out"),
        true
    )
)

Scala: A “sum of the squares” algorithm using map/sum and foldLeft

As a quick Scala fold/reduce example, I just needed to write a “sum of the squares” algorithm for a “Pearson Correlation” function I’m working on, and initially wrote it like this using map and sum:

val sumOfTheSquares = movieRatingsMap.values
                                     .map(rating => Math.pow(rating, 2))
                                     .sum

If you know Scala, and know that movieRatingsMap is a Map of movies and my ratings of those movies, I think that line of code is fairly easy to read. That line can also be written like this:

Scala 3, Scala CLI, JDBC, and SQL (examples)

As a brief “note to self” today, here are two examples of how to perform SQL queries with Scala 3, using (a) plain JDBC, and also (b) using a little Scala 3 library known as SimpleSQL. These examples use Scala CLI, which as I have mentioned before, makes these examples so much easier to share with you.

A Unix shell script to clean all SBT subdirectories

In a recent attempt at freeing up some disk space, I wrote this little Unix shell script to go through all of my Scala/SBT project directories, and run the sbt clean command in each directory:

#!/bin/sh

# WARNING: make sure you have backed up your files
# and directories before running this script.
for file in `cat sbt_dirs`
do
    dir=`dirname $file`
    echo "WORKING ON $dir"
    cd $dir
    sbt clean
    cd -
done

This script assumes that you have a list of the desired subdirectories in a file named sbt_dirs.

Sadly, I forgot to check the before and after disk space comparison, so I can only guess that it helped by deleting all the SBT project and target subdirectories it generates.

A Scala method to run any block of code slowly

The book, Advanced Scala with Cats, has a nice little Scala function you can use to run a block of code “slowly”:

def slowly[A](body: => A): A = 
    try
        body
    finally
        Thread.sleep(100)

I’d never seen a try/finally block written like that (without a catch clause), so it was something new for the brain.

In the book they run a factorial method slowly, like this:

slowly(factorial(n - 1).map(_ * n))

FWIW, you can modify slowly to pass in the length of time to sleep, like this:

def slowly[A](body: => A, sleepTime: Long): A =
    try
        body
    finally
        Thread.sleep(sleepTime)

Passing a block of code to a function in Scala (callbacks)

I've posted a lot of Scala source code examples out here lately, and as I keep trying to learn more about passing one function to another function in Scala (function callbacks), here's another example showing how you can use Scala's functional programming approach to clean up some Java Swing code:

Scala: How to build custom control structures with types and call-by-name parameters

(This article is an excerpt from the 1st Edition of the Scala Cookbook.)

To put what you’ve learned in this chapter to use, let’s create two examples:

  1. First, you’ll create a timer method that looks like a Scala control structure, and works like the Unix time command.
  2. Second, you’ll create another control structure that works like the Try/Success/Failure classes that were included with Scala 2.10.

Example 1: Creating a Scala Timer

On Unix systems you can run a time command (timex on some systems) to see how long commands take to execute:

$ time find . -name "*.scala"

A Scala cheat sheet (reference page)

Summary: This document is a Scala cheat sheet (reference page), in HTML format.

This page is very much a work in progress, but as I've been learning Scala, I've been creating all sorts of little notes, and I'm now trying to organize them into this Scala cheat sheet. These notes are based on the excellent books, Programming in Scala (Odersky, Spoon, and Venners), and Programming Scala (O'Reilly).

[toc hidden:1]

A Scala Spring Framework dependency injection example

Curious about how well Scala would play with the Spring Framework, I created a small Scala/Spring dependency injection example project, which I'm sharing here.

The short answer is that Scala worked just fine with Spring, but it also showed me that I still have plenty to learn about inheritance in Scala.

My Spring applicationContext.xml file

I copied a Spring applicationContext.xml file from another project, then whittled it down to these bare essentials:

[toc hidden:1]

Interval halving (Bisection) method in Scala (OOP and FP styles)

I just picked up an old college textbook named Applied Numerical Analysis, and curious to see what the Interval Halving method (also known as the Bisection Method) would look like in Scala, I decided to code it up. Considering that Scala is similar to the Java programming language, if anyone else needs the Interval-Halving method in Java, this code can easily be adapted to Java as well.

[toc hidden:1]

Scala List/Array/Vector/Seq class filter method examples

The Scala List class filter method implicitly loops over the List you supply, tests each element of the List with the function you supply. Your function must return true or false, and filter returns the list elements where your function returns true.

(Note: Even though I use a List in these examples, the filter method can be used on any Scala sequence, including Array, ArrayBuffer, List, Vector, Seq, etc.)

[toc hidden:1]

Making Twitter web service calls concurrently with Akka Futures

While I was working on improving how Sarah gets information from Twitter and other sources, I decided to take some of that code and hack together this example. It shows how to make three Twitter web service requests concurrently -- and then wait for ther results before moving on -- with Akka Futures.

Before sharing the entire class, the cool Akka Futures stuff is in these lines of code: