6.8. Creating 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.
Solution
There are two ways to do this:
Create a companion object for your class, and define an
apply
method in the companion object with the desired constructor signature.Define your class as a case class.
You’ll look at both approaches next.
Creating a companion object with an apply method
To demonstrate the first approach, define a Person
class and Person
object in the same file. Define an
apply
method in the object that
takes the desired parameters. This method is essentially the
constructor of your class:
class
Person
{
var
name
:
String
=
_
}
object
Person
{
def
apply
(
name
:
String
)
:
Person
=
{
var
p
=
new
Person
p
.
name
=
name
p
}
}
Given this definition, you can create new Person
instances without using the new
keyword, as shown in these
examples:
val
dawn
=
Person
(
"Dawn"
)
val
a
=
Array
(
Person
(
"Dan"
),
Person
(
"Elijah"
))
The apply
method in a
companion object is treated specially by the Scala compiler and lets
you create new instances of your class without requiring the new
keyword. (More on this in the
Discussion.)
Declare your class as a case class
The second solution to the problem is to declare your class as a case class, defining it with the desired constructor: ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.