Classes and Objects in Scala

 Classes and Objects in Scala


Scala is an object-oriented language, so classes and objects are fundamental concepts. Here's an example of a class:

kotlin


class Person(var name: String, var age: Int) {

  def greet(): Unit = {

    println(s"Hello, my name is $name and I'm $age years old.")

  }

}


val john = new Person("John", 30)

john.greet() // prints "Hello, my name is John and I'm 30 years old."

And here's an example of an object:


kotlin


object MathUtils {

  def add(x: Int, y: Int): Int = {

    return x + y

  }


  def multiply(x: Int, y: Int): Int = {

    return x * y

  }

}


val sum = MathUtils.add(2, 3) // sum is now 5

val product = MathUtils.multiply(2, 3) // product is now 6

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...