Introduction
The word “object” has a dual meaning in Scala. As with Java, you use
it to refer to an instance of a class, but in Scala, object
is also a keyword.
The first three recipes in this chapter look at an object as an
instance of a class, show how to cast objects from one type to another,
demonstrate the Scala equivalent of Java’s .class
approach, and show how to determine the
class of an object.
The remaining recipes demonstrate how the object
keyword is used for other purposes.
You’ll see how to use it to launch Scala applications and to create
Singletons. There’s also a special type of object known as a
package object. Using a package object is entirely
optional, but it provides a nice little out-of-the-way place where you can
put code that’s common to all classes and objects in a particular package
level in your application. For instance, Scala’s root-level package object
contains many lines of code like this:
type
Throwable
=
java
.
lang
.
Throwable
type
Exception
=
java
.
lang
.
Exception
type
Error
=
java
.
lang
.
Error
type
Seq
[
+A
]
=
scala
.
collection
.
Seq
[
A
]
val
Seq
=
scala
.
collection
.
Seq
Declaring those type definitions in Scala’s root package object helps to make the rest of the code a little bit cleaner, and also keeps these definitions from cluttering up other files.
You’ll also see how to create a companion object to solve several problems. For instance, one use of a companion object is to create the equivalent of Java’s static members. You can also use a companion object so consumers ...
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.