Register Login

Define Method and Function in Scala

Updated May 18, 2018

How to create methods in Scala?

Enter a keyword ‘def’ to define the function and then a function called show(). You need to use the ‘=’ operator to define a function.

def show() =
{
println("hi")
}

To get the output, call the method by entering show().

var s1 = Student(name = "Mohit"); //> s1 :Demo.Student = Student(1,Rahul,90)
s1.show() //>hi

In case you have only one line of code then you don’t need the curly brackets. See the example in the image below.

Go to Java, then New > class. Give a name and make sure that it has a ‘demo’ function.

Create two objects and then perform an operation to compare them.

Student s1 = new Student(1,"Veena",80);
Student s2 = new Student(2, "Mohit",90);

In Java, comparison of two object is done by methods. In this case the method is isGreater().

System.out.println(s1.isGreator(s2));

As this method does not exist, you need to create one inside the respective class.

public boolean isGreater(Student s2) {
// 1000 Auto-generated method stub
return marks > s2.marks;

In Scala, which supports operator overloading, you can compare two objects by –

var s2 = Student(2,"Mohit",) //. s2 : Demo.Student = Student(1,Veena,90)

 

Instead of suing methods to compare, you can also use a greater than symbol. But before using it, you need to define a function.

def >(s2 : Student) : Boolean = marks > s2.marks

  • var s1 = Student(); //> s1 : Demo.Student = Student(1,Veena,90
  • var s1 = Student(2,"Mohit",88); //> s2 : Demo.Student = Student(2,Mohit,88)

s1.>(s2) ///> res0: Boolean = true

  • var s1 = Student(); .//> s1 : demo.Student = Student(1,Veena,90)
  • var s2 = Student(2,"Mohit",98) //>s2 : Demo.Student = Student(2,Mohit,98)

s1.>(s2) //> res0: Boolean = false


×