Class Basics
A class is a blueprint that describes what things of one kind know and can do, like the plan for a toy car. You use it to make as many toy cars as you want.
In this page:
Syntax
class ClassName {
// fields
// methods
}
val instance = new ClassName
Class Basics
A Scala class is declared with class ClassName { ... }, bundling data and behavior into a blueprint you instantiate with new.
Unlike some languages, a class's primary constructor parameters can be declared directly in the class signature, like class Point(x: Int, y: Int). Every value in Scala, including numbers, is technically an object of some class.
Note:
Constructor parameters declared directly in the class signature avoid needing a separate explicit constructor block for the common case.
Example: Class Basics
class Dog(name: String) {
def bark(): Unit = {
println(s"$name says Woof!")
}
}
object Main extends App {
val rex = new Dog("Rex")
rex.bark()
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Creating an object without
newin Scala 2, as inDog("Rex")for a plain class, which does not compile; only case classes getapply. - Calling
rex.namefor a plain constructor parameter, which is private to the class unless declared asval. - Using
class Dog { def bark = ... }insideobject Main extends Appand forgetting to instantiate it before calling its methods.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: