Christian Yonathan S.
Christian Yonathan S.

Reputation: 185

What is mean method Apply on Scala

according to this link example
and then im create code like this :

    object objPersamaan{
      def main(args : Array[String]){
        val x = objPersamaan("Budi ")
        println(x)
      }
      def apply(pX:String) = pX + "Belajar"
      def unapply(pZ:Int) : Option[Int] = if(pZ%2==0) Some(pZ/2) else None
    }

i can't still dont understand, how can objPersamaan("Budi ") would had value Budi Belajar? is that method apply like constructor with parameter? or what? can anyone, explain more detail why the process from method apply? thanks!

Upvotes: 0

Views: 54

Answers (1)

Martin Seeler
Martin Seeler

Reputation: 6982

In Scala, you can omit the method name apply. So calling objPersamaan("Budi ") is the same as objPersamaan.apply("Budi "), which then concatenates the String Belajar to the given parameter.

When you have an object and call it without a method name, just your arguments, the copmiler expands this call with MyObject.apply(...). This comes from the fact, that you often use objects where you want to apply something to (e.g. in factories), so Scala built this feature directly into the language.

case class MyObj(foo: String, bar: String)
object MyObj {
  def apply(x: Int): MyObj = MyObj(x.toBinaryString, x.toHexString)
}

// ...
MyObj(42)
// same as
MyObj.apply(42)

Upvotes: 5

Related Questions