Scala – Apply Method

  • date 23rd April, 2021 |
  • by Prwatech |

In Scala the apply() method is used to select an element present in the list by its index position.

use case 1:

scala> object prwa{

     def apply(name: String): String={

     “Hello %s”.format(name)



object prwa

scala> prwa.apply(“prava”)

scala> prwa(“binoj”)

use case 2:

scala> class Prwatech  {

     private val elements = Array(“spark”,”scala”,”mysql”)

  def apply(index:Int) = if(index<elements.length) elements(index) else “No element found”


class Prwatech

scala> val Prwatech = new Prwatech

scala> println(Prwatech(1))

scala> println(Prwatech(0))

scala> println(Prwatech(2))

scala> println(Prwatech(3))

use case 3:

Scala> object prwatech{

     def apply(name: String): String={

     “My Name is %s”.format(name)



object prwatech

scala> prwatech.apply(“Mark”)

scala> prwatech.apply(“Steve”)

Quick Support

image image