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 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.