instance

How to dynamically add a Scala trait to an object instance alvin June 14, 2015 - 4:16pm

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a very short recipe, Recipe 8.8, “How to dynamically add a Scala trait to an object instance.”

Problem

Rather than add a trait to an entire class, you just want to add a trait to an object instance when the object is created.

Solution

Add the trait to the object when you construct it. This is demonstrated in a simple example:

How to create Scala object instances without using the “new” keyword (apply)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 6.8, “How to create object instances without using the 'new' keyword.”

Problem

You’ve seen that Scala code looks cleaner when you don’t always have to use the new keyword to create a new instance of a class, like this:

val a = Array(Person("John"), Person("Paul"))

So you want to know how to write your code to make your classes work like this.

Scala “object” examples

This article is a collection of Scala “object” examples. I put the word object in quotes there because it has at least two meanings in Scala. In the first meaning, just like Java, an object is an instance of a class.

In its second meaning, Scala has an object keyword, and using that keyword lets you do a variety of things, including creating a main method to launch your application, to create the equivalent of Java’s static methods, and also to create something called a companion object.