[英]How does apply() work on a companion object for a trait?
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. 在代码中,当我可以理解正在调用apply时。 But I am not able to understand: 但我无法理解:
Sample{"World"}
? 此语法是什么意思: Sample{"World"}
? What is it called as and how does it invoke apply()
? 它称为什么,以及它如何调用apply()
? body: => String
in apply()
mean? body: => String
apply()
body: => String
是什么意思? Why does it give me an error if there is no space between body:
and =>
? 如果body:
和=>
之间没有空格,为什么会给我一个错误? java.lang.String
as return instead of just String
? 为什么要求我键入java.lang.String
作为return而不是String
? What does this syntax mean: Sample{"World"}? 此语法是什么意思:Sample {“ World”}? What is it called as and how does it invoke apply()? 它称为什么,以及它如何调用apply()?
=> It's syntactic sugar
where Scala compiler converts Sample("World")
or Sample{"World"}
to Sample.apply("World")
. => Scala编译器将Sample("World")
或Sample{"World"}
为Sample.apply("World")
的syntactic sugar
。 for eg: when you create a list 例如:创建列表时
val list = List(1,2,3)
The compiler actually converts it to List.apply(1,2,3)
编译器实际上将其转换为List.apply(1,2,3)
What does body: => String in apply() mean? 正文:=> apply()中的字符串是什么意思? Why does it give me an error if there is no space between body: and =>? 如果body:和=>之间没有空格,为什么会给我一个错误?
=> Its an illustration of call by name
parameter in scala.Here, body
is a call by name
parameter. =>它是Scala中call by name
参数call by name
的图示。在此, body
是call by name
参数call by name
。 And such parameters have the syntax where you must put a space between : and =>
. 这些参数具有必须在: 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? 为什么它要求我键入java.lang.String作为return而不是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: =>首先,您需要清楚scala中的String
是java.lang.String
的别名。如果在scala.Predef
内部scala.Predef
,您将发现:
type String = java.lang.String
So, we are actually using the same java.lang.String
in scala all the time. 因此,实际上我们一直在Scala中使用相同的java.lang.String
。
Secondly, in your apply method: 其次,在您的apply方法中:
def apply[String](body: => String)
apply[String]
is not using the scala String
, its using a type parameter
. apply[String]
没有使用scala String
,而是使用type parameter
。 What I mean is you could also write your apply method as: 我的意思是,您也可以将apply方法编写为:
def apply[T](body: => T):java.lang.String
And it would work the same way. 它将以相同的方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.