Thursday, 17 September 2020

Scala: Infix notation of methods

If a method ‘op’ takes one argument then ‘a op b’ is same as a.op(b).

 

For example,

1.until(5) is same as ‘1 until 5’.

scala> 1 until 5
val res237: scala.collection.immutable.Range = Range 1 until 5

scala> 1.until(5)
val res238: scala.collection.immutable.Range = Range 1 until 5

 

Example 2: Similarly 1.to(5) is same as ‘1 to 5’.

 

scala> 1.to(5)
val res239: scala.collection.immutable.Range.Inclusive = Range 1 to 5

scala> 1 to 5
val res240: scala.collection.immutable.Range.Inclusive = Range 1 to 5

 

Example 3: "#" * 5 is same as "#".*(5)

scala> "#" * 5
val res242: String = #####

scala> "#".*(5)
val res243: String = #####

 

Let’s define method with single argument and experiment with it in both infix notation and general form.

class User(firstName: String, lastName: String) {

  def welcome(message: String) = {
    s"$message $firstName,$lastName"
  }
}

 

Above snippet defines ‘welcome’ method that takes single argument.

 

Let’s define a User instance.

val user1 = new User("Krishna", "Gurram")

 

Now you can call welcome method in both infix notation and normal form.

 

user1.welcome("Good Morning")

user1 welcome "Good Morning"

scala> class User(firstName: String, lastName: String) {
     | 
     |   def welcome(message: String) = {
     |     s"$message $firstName,$lastName"
     |   }
     | }
class User

scala> val user1 = new User("Krishna", "Gurram") 
val user1: User = User@cf87deb

scala> user1.welcome("Good Morning")
val res244: String = Good Morning Krishna,Gurram

scala> user1 welcome "Good Morning"
val res245: String = Good Morning Krishna,Gurram

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment