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.