What is the method of defining classes in Scala?

In Scala, you can use the keyword “class” to define classes. The methods of a class can be implemented by defining member functions within the class. Member functions can be defined either within the class itself or in a companion object.

Below is an example.

class MyClass {
  def hello(): Unit = {
    println("Hello, Scala!")
  }
}

object MyClass {
  def main(args: Array[String]): Unit = {
    val myObject = new MyClass()
    myObject.hello()
  }
}

In the example above, the class MyClass defines a member function named hello that prints a message. We create a MyClass object in the companion object of MyClass and call its hello method. Executing this code will output Hello, Scala!

In addition to member functions, it is possible to define member variables, constructors, and other class features within a class. Scala also supports concepts such as traits and abstract classes, which can further enhance the functionality of a class.

广告
Closing in 10 seconds
bannerAds