“20 秒”在 Scala 中是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15104536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does '20 seconds' work in Scala?
提问by ripper234
How does the following compile:
以下如何编译:
import scala.concurrent.duration._
val time = 20 seconds
What is actually going on here?
这里究竟发生了什么?
回答by Aaron Novstrup
There are a few things going on.
有几件事正在发生。
First, Scala allows dots and parens to be omitted from many method calls, so 20 secondsis equivalent to 20.seconds()*.
首先,Scala 允许在许多方法调用中省略点和括号,所以20 seconds等价于20.seconds()*.
Second, an "implicit conversion" is applied. Since 20is an Intand Inthas no secondsmethod, the compiler searches for an implicit conversion that takes an Intand returns something that does havea secondsmethod, with the search constrained by the scope of your method call.
其次,应用了“隐式转换”。由于20是Int和Int没有seconds方法,因为这需要一个隐式转换编译器搜索Int和返回的东西,确实有一个seconds方法,通过你的方法调用的范围限制搜索。
You have imported DurationIntinto your scope. Since DurationIntis an implicit class with an Intparameter, its constructor defines an implicit Int => DurationIntconversion. DurationInthas a secondsmethod, so it satisfies all the search criteria. Therefore, the compiler rewrites your call as new DurationInt(20).seconds**.
您已将DurationInt导入您的范围。由于DurationInt是一个带Int参数的隐式类,它的构造函数定义了一个隐式Int => DurationInt转换。DurationInt有一个seconds方法,所以它满足所有的搜索条件。因此,编译器将您的调用重写为new DurationInt(20).seconds**。
*I mean this loosely. 20.seconds()is actually invalid because the secondsmethod has no parameter list and therefore the parens mustbe omitted on the method call.
*我的意思是松散的。20.seconds()实际上是无效的,因为该seconds方法没有参数列表,因此在方法调用中必须省略括号。
**Actually, this isn't quite true because DurationIntis a value class, so the compiler will avoid wrapping the integer if possible.
**实际上,这并不完全正确,因为它DurationInt是一个值类,因此编译器将尽可能避免包装整数。
回答by Bruno Reis
The "magic" that's going on there is called "implicit conversion". You are importing the implicit conversions, and some of them handle the conversion between Int (and Double) to Duration. That's what's you are dealing with.
那里发生的“魔法”被称为“隐式转换”。您正在导入隐式转换,其中一些处理 Int(和 Double)到 Duration 之间的转换。这就是你正在处理的事情。

