Posts in the “scala” category

Using the Scala Option, Some, and None idiom (instead of Java null)

A powerful Scala idiom is to use the Option class when returning a value from a function that can be null. Simply stated, instead of returning one object when a function succeeds and null when it fails, your function should instead return an instance of an Option, where the instance is either:

  1. In the success case, return an instance of the Scala Some class
  2. In the failure case, return an instance of the Scala None class

Because Some and None are both children of Option, your function signature just declares that you're returning an Option that contains some type (such as the Int type shown below). At the very least, this has the tremendous benefit of letting the user of your function know what’s going on.

Learn Scala 3 The Fast Way (book)

I’ve been slowly working on a series of new Scala programming books, and today I’m proud to announce the first of these:

Learn Scala 3 The Fast Way! (book cover)

Starting today you can buy the PDF version of Learn Scala 3 The Fast Way! for just ten dollars — $10 (USD) — at this Gumroad.com URL.

Book: Learn Functional Programming The Fast Way! (FP for OOP developers)

MARCH, 2023: This book was previously named Learn Functional Programming Without Fear, but I have renamed it to Learn Functional Programming The Fast Way. I think this name is more reflective of the ZIO and Cats Effect libraries being easier to learn than ever before (without having to know category theory), and the name is also consistent with my other book, Learn Scala 3 The Fast Way.

NOV., 2022: My new book, Learn Functional Programming Without Fear, is currently an Amazon Java and functional programming #1 new release. The book is now available in three formats:

PDF Format
$10 (USD) on Gumroad.com

Learn Functional Programming The Fast Way! (PDF Version)

Paperback
$30 on Amazon

Learn Functional Programming The Fast Way (Paperback)

Kindle
$10 on Amazon

Learn Functional Programming The Fast Way! (Kindle Edition)

Scala money and currency: The BigDecimal class and libraries

Note: I don't have any immediate solutions in this article; it's more of a discussion of where I'm at today when looking at handling money/currency in Scala.

As a quick note, I've started to look at handling money/currency in Scala, and I'm also starting to explore a couple of money/currency libraries.

A Scala shell script example (and discussion)

Scala shell script FAQ: How do I create a Unix/Linux shell script to run a small Scala script?

If you want to run a Scala script as a Unix or Linux shell script -- such as hello.sh -- write your script like this:

Scala 3: An apply/factory method that takes a varargs/tuple parameter

Here’s a brief Scala 3 example that shows how to:

  1. Create a companion object,
  2. Create an apply method in that companion object that acts as a factory method,
  3. Define that apply method to take a varargs tuple parameter, and
  4. Create new Person instances using that factory method.

Here’s the complete source code for this example:

Scala 3 dates: How to parse strings into dates (LocalDate, DateTimeFormatter)

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 3.12, Parsing Strings Into Dates.

Problem

While using Scala (Scala 2 or 3), you need to parse a String into one of the date/time types introduced in Java 8.

Solution

If your String is already in the expected format, pass it to the parse method of the desired class. If the String is not in the expected (default) format, create a formatter to define the format you want to accept. The following examples demonstrate the expected formats, and other solutions.

Scala tuple examples and syntax

Scala FAQ: Can you share some examples of using tuples in Scala?

A Scala tuple is a class that can contain a miscellaneous collection of elements. I like to think of them as a little bag or container you can use to hold things and pass them around.

You create a tuple with the following syntax, enclosing its elements in parentheses. Here's a tuple that contains an Int and a String:

[toc hidden:1]

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
    )
)

Functional programming books, comparison

Since I’ve written two functional programming (FP) books, I thought it might help to provide a comparison of them.

The short story is that both FP books have “limited technical jargon,” and as shown, The Little FP Book essentially has one purpose, which is to help Java/Kotlin/OOP developers learn functional programming as fast as possible, using a technique that I “discovered” over the last few years. Conversely, The Big FP Book covers many topics in great detail.

If you’re interested in more details, here are links to the two books:

Scala “split string” examples (field separator, delimiter)

Scala String FAQ: How do I split a String in Scala based on a field separator, such as a String I get from a comma-separated value (CSV) file or pipe-delimited file.

Solution

Use one of the split methods that are available on Scala/Java String objects. For instance, this example in the Scala REPL shows how to split a string based on a blank space: