Creating and Using Classes

Creating classes in Scala is shockingly expressive and highly concise. We’re going to explore how to create instances first, then how to create classes, and finally how to define fields and methods.

Creating Instances

Creating an instance of a class in Scala is not much different from creating instances in Java. For example, let’s create an instance of StringBuilder:

 
new​ ​StringBuilder​(​"hello"​)

That’s pretty much like in Java, except for the missing semicolon. We used new followed by the class name and the argument(s) for its constructor. The class StringBuilder has another overloaded constructor that doesn’t take any parameters. Let’s use that next:

 
new​ ​StringBuilder​()

That worked, but Scala programmers ...

Get Pragmatic Scala now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.