companion object

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.

How to create static members with Scala companion objects

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 6.6, “How to create static members with Scala companion objects.”

Problem

You want to create a class that has instance methods and static methods, but unlike Java, Scala does not have a static keyword.