Posts in the “scala” category

Scala: What is the Nothing data type?

In Scala, Nothing is a bottom type, which means it is a subtype of every other type in the type system. It represents a data type that has no instances.

Essentially, Nothing is used to indicate that a computation or function will never produce a result normally, either because it throws an exception, enters an infinite loop, or encounters some other abnormal termination.

Visually, this is what the Nothing type looks like in the Scala type hierarchy (image courtesy of this scala-lang.org page):

The Scala type hierarchy and the Nothing data type

Scala: Common uses of Nothing

Some common use cases of Nothing include:

Scala: How to square a number (Int, Double, Float, Long)

[toc]

Scala math FAQ: How do I square a number in Scala, such as squaring an Int, Double, Long, or Float?

Solution

You can square a number in Scala in at least two different ways:

  1. Multiply the number by itself
  2. Call the Java Math.pow function or the scala.math.pow function

How to iterate over Scala Lists with foreach and for

[toc]

Scala List/sequence FAQ: How do I iterate over a Scala List (or more generally, a Scala sequence) using the foreach method or for loop?

There are a number of ways to iterate over a Scala List using the foreach method — which is available to Scala sequences like List, Array, ArrayBuffer, Vector, Seq, etc. — and the for comprehension, and I'll show a few of those approaches here.

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

[toc]

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. This example shows how to split a string based on a blank space:

How to add elements to a List in Scala (List, ListBuffer)

Scala List FAQ: How do I add elements to a Scala List?

"How do I add elements to a Scala List” is actually a trick question, because you can't add elements to a Scala List; it's an immutable data structure, like a Java String. In the following sections I’ll show what you can do.

Prepending elements to Scala Lists

The most common ways to add elements to a Scala List is to create a new List from an existing List by prepending elements to the existing list. This sort of thing is done often in functional programming in Scala, and the general approach looks like this:

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: How to define a generic method parameter that must extend a base type (bounds)

In today’s installation of “how to have fun with Scala,” if you want to (a) define a Scala method that takes an input parameter, and (b) that parameter has a generic type, and (c) you further want to further declare that the parameter must extend some base type, then (d) use this “bounds” syntax:

def getName[A <: RequiredBaseType](a: A) = ???

This example can be read as, “The parameter a has the generic type A, and A must be a subtype of RequiredBaseType.”

A complete Scala bounds example

As a concrete example of how using bounds works, start with a simple base type, such as this Scala trait:

trait SentientBeing {
    def name: String
}

Next, extend that base trait with a few more traits:

trait AnimalWithLegs extends SentientBeing
trait TwoLeggedAnimal extends AnimalWithLegs
trait FourLeggedAnimal extends AnimalWithLegs

Then extend those with some concrete case classes:

case class Dog(name: String) extends FourLeggedAnimal
case class Person(name: String, age: Int) extends TwoLeggedAnimal
case class Snake(name: String) extends SentientBeing

Notice that Snake extends SentientBeing, but not AnimalWithLegs.

Now that you have all the types you need, define a method that takes a parameter that has a generic type that must extend some base type. To see how everything works, define it this way the first time:

def getName[A <: SentientBeing](a: A): String = a.name

Because the base type (or “super type”) is SentientBeing, all of these calls work just fine:

getName(Person("Fred", 20))
getName(Dog("Rover"))
getName(Snake("Noodles"))

(Copy and paste those into the Scala REPL if you want to verify they work as advertised.)

Now extend AnimalWithLegs

Next, change getName so the generic type A must be a subtype of AnimalWithLegs:

def getName[A <: AnimalWithLegs](a: A): String = a.name

Now, when you run the same three method calls again, you’ll see that the Snake example fails because it doesn’t extend AnimalWithLegs:

getName(Person("Fred", 20))
getName(Dog("Rover"))
getName(Snake("Noodles"))   //error

Here’s what the two sets of getName examples look like in the Scala REPL:

Show a Scala method with generic type parameter

(Right-click that image and select “View image” to see it larger.)

The Scala “type parameter bounds” error

As shown, the second Snake example results in this error message:

scala> getName(Snake("Noodles"))
<console>:15: error: inferred type arguments [Snake] do not conform to method getName's 
type parameter bounds [A <: AnimalWithLegs]
       getName(Snake("Noodles"))
       ^
<console>:15: error: type mismatch;
 found   : Snake
 required: A
       getName(Snake("Noodles"))
                    ^

This is because the type Snake does not extend AnimalWithLegs. (At least not in my world.)

Technical matters: ‘A’ has an “upper bound”

Technically what’s happening here is that I’m defining A with an “upper bound.” Bounds let you place restrictions on type parameters, and in this example I’m saying, “A must be a subtype of the type AnimalWithLegs”:

def getName[A <: AnimalWithLegs](a: A): String = a.name

More generally, this is how you say, “A must be a subtype of B”:

A <: B

I write more about this topic in, An introduction to Scala Types, so please see that article for a few more details.

How to read “difficult” Scala method type signatures

When I first saw Scala generic type and multiple-parameter group code like this ~12 years ago, my initial thought was, “Wow, maybe I need to think about a different career”:

def race[A, B](lh: IO[A], rh: IO[B])(implicit cs: ContextShift[IO]): IO[Either[A, B]]

But in the end, as Rocky once said, it ain’t so bad. :)

Rocky: You ain’t so bad

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

Scala 3 dates: How to calculate the difference between two dates (LocalDate, ChronoUnit)

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 3.10, Calculating The Difference Between Two Dates.

Problem

While using Scala (Scala 2 or 3), you need to determine the difference between two dates.

Scala Solution: Difference between two dates

If you need to determine the number of days between two dates, the DAYS enum constant of the java.time.temporal.ChronoUnit class is the easiest solution:

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

Scala 3: Creating New Date and Time Instances

This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 3.9, Creating New Date and Time Instances.

Problem

In Scala, you need to create new date and time instances using the Date and Time API that was introduced with Java 8.

Solution: Dates and times in Scala

Using the Java 8 API you can create new dates, times, and date/time values. Descriptions of common Java 8 Date and Time classes provides a description of some of the new classes you’ll use (from the java.time Javadoc), all of which work in the ISO-8601 calendar system.

A Scala current date and time example

Scala date/time FAQ: How do I get the current date and time in Scala?

Getting the current time

The following code demonstrates how to get the current time in Scala, and then further shows how to get other information, such as the current minute, using the Java SimpleDateFormat class:

[toc hidden:1]