3

I' new to scala and recently I came across the following piece of code:

object Foo {
    implicit lazy val myGlobalExecutionContext: ExecutionContextExecutor =
    impl.ExecutionContextImpl.fromExecutor(null: Executor)
}

I have checked the fromExecutor signature and it's like this

def fromExecutor(e: Executor): ExecutionContextExecutor

My question is why did we do :

impl.ExecutionContextImpl.fromExecutor(null: Executor)

and not simply

impl.ExecutionContextImpl.fromExecutor(null)

And why do we pass a type of the parameter when invoking a method?

1 Answer 1

6

I don't see any particular reason in this case, but fromExecutor could be overloaded, and we might want to ensure a particular overload is called. For example:

case class Bar(id: Int)
case object Baz

object Test {
    def fromBar(bar: Bar): Bar = bar
    def fromBar(baz: Baz): Bar = Bar(0)
}

If I call:

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)

I get an error because the call is ambiguous. null could be Bar or Baz. So I must use a type cast or ascription to use a specific overload:

 Test.fromBar(null: Bar)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.