create

How to create and populate Kotlin lists (initialize mutable and immutable lists)

If you ever need to create and populate a Kotlin list, I can confirm that these approaches work for an immutable and mutable lists:

// fill an immutable list
val doubles = List(5) { i -> i * 2 }

// fill a mutable list of ten elements with zeros
val ints = MutableList(10) { 0 }

The Kotlin REPL shows how these approaches work:

An Effective Java note on reusing existing Exception classes alvin October 29, 2018 - 11:48am

I just read a short chapter in the book Effective Java, and realized I was doing something pretty dumb in my own code by always creating my own custom exceptions instead of using other exceptions already intended to be reused in the Java API.

Scala ArrayBuffer class: methods, syntax, and examples alvin August 16, 2018 - 12:33pm

This page contains a large collection of examples of how to use the Scala ArrayBuffer class.

Use the ArrayBuffer class when you want to use a general-purpose, mutable indexed sequence in your Scala applications:

Scala Array class: methods, examples, and syntax alvin June 16, 2018 - 5:09pm

This page contains a large collection of examples of how to use the methods on the Scala Array class.

How to create an empty Scala Map

If you need to create an empty Map in Scala, the following examples show how to create empty immutable and mutable maps.

An empty immutable Map

You can use these approaches to create an empty immutable Scala Map:

val a = Map[Int, String]()
val a = Map.empty[Int, String]

Here’s what they look like in the REPL:

Scala List class: methods, examples, and syntax alvin May 22, 2018 - 1:00pm

This page contains a large collection of examples of how to use the methods on the Scala List class.

The Scala List class as an immutable, linear, linked-list class. It’s very efficient when it makes sense for your algorithms to (a) prepend all new elements, (b) work with it in terms of its head and tail elements, and (c) use functional methods that traverse the list from beginning to end, such as filter, map, foldLeft, reduceLeft.

Scala Seq class: methods, examples, and syntax alvin May 21, 2018 - 5:47pm

This page contains a large collection of examples of how to use the methods on the Scala Seq class.

Important note about Seq, IndexedSeq, and LinearSeq

As an important note, I use Seq in the following examples to keep things simple, but in your code you should be more precise and use IndexedSeq or LinearSeq where appropriate. As the Seq class Scaladoc states:

Scala Vector class: method examples and syntax alvin May 20, 2018 - 10:44pm

This page contains a large collection of examples of how to use the Scala Vector class, including most of the methods that are available on a Vector. (Currently over 170 examples.)