0

Consider the below code:

object Rough extends App {
  trait Sample

  object Sample {
    def apply[String](body: => String): java.lang.String = {
      "Hello " + body
    }
  }

  val s: String = Sample {
    "World"
  }
  print(s)
}

In the code, when I can understand that the apply is being called. But I am not able to understand:

  1. What does this syntax mean: Sample{"World"}? What is it called as and how does it invoke apply()?
  2. What does body: => String in apply() mean? Why does it give me an error if there is no space between body: and =>?
  3. Why does it ask me to type java.lang.String as return instead of just String?
codingsplash
  • 4,785
  • 12
  • 51
  • 90

1 Answers1

4

What does this syntax mean: Sample{"World"}? What is it called as and how does it invoke apply()?

=> It's syntactic sugar where Scala compiler converts Sample("World") or Sample{"World"} to Sample.apply("World") . for eg: when you create a list

val list  = List(1,2,3) 

The compiler actually converts it to List.apply(1,2,3)

What does body: => String in apply() mean? Why does it give me an error if there is no space between body: and =>?

=> Its an illustration of call by name parameter in scala.Here, body is a call by name parameter. And such parameters have the syntax where you must put a space between : and =>. For more information, you could see call by name Vs call be value

Why does it ask me to type java.lang.String as return instead of just String?

=> Firstly, you need to be clear that the String in scala is an alias for java.lang.String.If you see inside scala.Predef, you will find:

type String = java.lang.String

So, we are actually using the same java.lang.String in scala all the time.

Secondly, in your apply method:

def apply[String](body: => String)

apply[String] is not using the scala String, its using a type parameter. What I mean is you could also write your apply method as:

def apply[T](body: => T):java.lang.String 

And it would work the same way.

Community
  • 1
  • 1
oblivion
  • 5,928
  • 3
  • 34
  • 55