Scala object and class

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-08 10:48:06 Viewed : 227


Scala object and class

·        Here is a simple class definition in Scala

class MyClassName{

}    

        var s = new MyClassName () // Creating an object

·        Define a  Scala class constructor 

class Employee(var firstName: String, var lastName: String) {

    def printFullName() = println(s"$firstName $lastName")

}

Notice that there’s no need to create “get” and “set” methods to access the fields in the class.

Example:

Following example illustrates about Scala object and class

Save the file as −  Employee.scala. 


 Employee.scala 

package runnerdev 

class Employee {

  var id: Int = 11 // All fields must be initialized

  var name: String = "Ram"

}

object ClassAndObject {

  def main(args: Array[String]) {

    var s = new Employee() // Creating an object

    println(s.id + " " + s.name)

  }

compile and run the above example as follows 

scala> scalac Employee.scala

scala> scala Employee

OutPut:

11 Ram


Example:

Following example illustrates about Scala class constructor    

class Point(var x: Int, var y: Int) { 

  def move(dx: Int, dy: Int): Unit = {

    x = x + dx

    y = y + dy

  }

 override def toString: String =

    s"($x, $y)"

} 

val point1 = new Point(2, 3)

println(point1.x)  // 2

println(point1)  // prints (2, 3)

Search
Sub-Categories
Related Articles

Leave a Comment:
mundVigum
at 2022-04-12 19:45:42
Harsh blowing holosystolic murmur with thrill At fourth left intercostal space Murmur decreases with Valsalva and handgrip The smaller the defect the louder the holosystolic murmur b. https://bestadalafil.com/ - cialis coupons Jauiek <a href="https://bestadalafil.com/">Cialis</a> Qtbern Kamagra France Fast Ship Viagra https://bestadalafil.com/ - Cialis Mpzkyg