显式null参数

ppo*_*ani 3 scala

我是scala的新手,最近我遇到了以下代码:

object Foo {
    implicit lazy val myGlobalExecutionContext: ExecutionContextExecutor =
    impl.ExecutionContextImpl.fromExecutor(null: Executor)
}
Run Code Online (Sandbox Code Playgroud)

我检查了fromExecutor签名,就像这样

def fromExecutor(e: Executor): ExecutionContextExecutor
Run Code Online (Sandbox Code Playgroud)

我的问题是我们为什么这样做:

impl.ExecutionContextImpl.fromExecutor(null: Executor)
Run Code Online (Sandbox Code Playgroud)

而不是简单的

impl.ExecutionContextImpl.fromExecutor(null)
Run Code Online (Sandbox Code Playgroud)

为什么我们在调用方法时传递一种参数?

Mic*_*jac 6

在这种情况下我没有看到任何特殊原因,但fromExecutor可能会重载,我们可能希望确保调用特定的重载.例如:

case class Bar(id: Int)
case object Baz

object Test {
    def fromBar(bar: Bar): Bar = bar
    def fromBar(baz: Baz): Bar = Bar(0)
}
Run Code Online (Sandbox Code Playgroud)

如果我打电话:

scala> Test.fromBar(null)
<console>:20: error: ambiguous reference to overloaded definition,
both method fromBar in object Test of type (baz: Baz)Bar
and  method fromBar in object Test of type (bar: Bar)Bar
match argument types (Null)
              Test.fromBar(null)
Run Code Online (Sandbox Code Playgroud)

我收到错误,因为调用不明确.null可能是BarBaz.所以我必须使用类型转换或ascription来使用特定的重载:

 Test.fromBar(null: Bar)
Run Code Online (Sandbox Code Playgroud)