TL ; DR:
A class is a blueprint for creating objects. It groups together related data and behavior under a single name.
In Scala, you define a class with the
classkeyword, followed by the class name and a pair of curly braces:class Dog { }
The body of the class can be empty — that's still a valid class. We'll add data and behavior to it in the next lessons.
Full lesson:
So far, you've worked with built-in types like Int, String, and arrays. But what if you want to model something the language doesn't have a type for — like a Dog, a BankAccount, or a Game?
That's what classes are for. A class lets you define your own type by listing what data it holds and what actions it can perform.
Why classes?
Imagine you're writing a program about dogs. Each dog has a name, an age, and can bark. Without classes, you'd have to track each dog's name in one variable, age in another, and write a separate bark() function for each. That gets messy fast.
With a class, you bundle all of that into one neat package called Dog:
class Dog {
// We'll add fields (data) and methods (behavior) here in upcoming lessons.
}
The syntax
Defining an empty class in Scala looks like this:
class ClassName {
}
Three things to notice:
The keyword
classtells Scala you're defining a new type.ClassNameis the name you choose. By convention, Scala class names use PascalCase — capitalized words with no underscores:Dog,BankAccount,HighScore.The curly braces
{ }hold the body of the class. They can be empty for now.
Your task
Define an empty class called Dog. The pre-filled code in mainFunction will create an instance of your class and print a confirmation message. If you define the class correctly, the program will compile and print:
Defined the Dog class!Free plan: 30 tutor messages. Premium is unlimited.