Scala tips

How to import only several classes from the same package ?

Scala provides an interesting feature of importing different classes from the same package by using {} clause. If we wan to import classes PersonDto and WorkerDto from package com.waitingforcode.dto, ...

Continue Reading →

How to set superclass field value before its initialization ?

Overriding fields and properties in Scala is straightforward. To do that we can simply use the override keyword. However, it doesn't apply for the case when the superclass needs the overridden values ...

Continue Reading →

How to ensure O(log n) insert complexity without loops ?

Loops are widely used in programming. We use them to iterate through the elements of one collection or to implement a sorting algorithm like in the following snippet: behavior of "priority queue"...

Continue Reading →

How to create a list with n the same elements in Scala ?

Thanks to the withDefault(...) method, Scala has a very easy practical and easy way to define the default value for a key not present in the map. Unfortunately, the sequences don't benefit from this b...

Continue Reading →

How to generate tuples from Scala's sequence ?

Scala's collection have a lot of interesting methods like grouped, take and drop. Another one that I didn't know was sliding. It behaves like a sliding window, i.e. it always takes X elements where th...

Continue Reading →

How to apply a different transformation for the last element of a sequence in Scala ?

Mapping Scala's sequence elements is easy when the mapping logic is the same for all items. However, sometimes you may want to apply different transformation to the first or the last element of the li...

Continue Reading →

How to build a JOIN condition from 2 Scala sequences?

We have 2 sequences. Each of them contains the columns that should be used to make a JOIN between 2 different tables in a database. How to create this query with Scala? First, we'll need a function...

Continue Reading →

How to get all fields of a case class in Scala?

Often case classes represent the data moved further in the pipeline. For example, they can represent JSON data that will be written into your data warehouse storage or an RDBMS. If for whatever rea...

Continue Reading →

How to define a function in Scala?

There are multiple ways to do that. You can of course extends Function1[Input, Output] (let's focus only on unary functions). Actually, there is also another, more idiomatic manner to write a function...

Continue Reading →