Scala implicit conversion on call-by-name parameter works differently depending on the function is overloaded or not
Asked Answered
C

1

7

Let's see the code below:

import scala.language.implicitConversions
class Foo
implicit def int2Foo(a: => Int): Foo = new Foo
def bar(foo: Foo) = {}
def bar(foo: Boolean) = {}
bar {
  println("Hello")
  64
}

This code does not print anything, because the block contains println("Hello") treated as => Int and it is converted to Foo by int2Foo. But the surprising thing is happen if we omit the overloaded function bar(foo: Boolean)

import scala.language.implicitConversions
class Foo
implicit def int2Foo(a: => Int): Foo = new Foo
def bar(foo: Foo) = {}
bar {
  println("Hello")
  64
}

This prints Hello because it evaluates the block, and only the last statement, 64 in this case, is treated as a call-by-name parameter. I cannot understand what kind of rationale exists behind of this difference.

Case answered 7/7, 2015 at 14:35 Comment(3)
Related issue: issues.scala-lang.org/browse/SI-3237Westleigh
There's no way this behavior is intended, unless I'm missing something. Even if it conforms to the spec, it's extremely counterintuitive and is seriously bug prone (e.g. what if somebody removes an overload that is apparently used nowhere, thereby causing the by-name parameter to behave differently).Westleigh
Wrapping the block in {...}:Int also changes the behavior.Westleigh
W
1

I think the Scala specification is ambiguous about how implicit views should be applied here. In other words, both of the following interpretations of the statement conform to the spec:

bar { println("Hello"); int2Foo(64) }
bar { int2Foo({ println("Hello"); 64 }) }

Of course, it is extremely counterintuitive for an unrelated overload to affect this behavior. It seems to me that the behavior, although ambiguous, should at least be consistent. This must be an implementation detail of the compiler interactions between overload resolution, by-name parameters, and implicit views. I have filed SI-9386 to address the issue.

Westleigh answered 8/7, 2015 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.