Skip to content

Instantly share code, notes, and snippets.

@gabro
Last active September 4, 2015 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabro/a98246e59585cc425160 to your computer and use it in GitHub Desktop.
Save gabro/a98246e59585cc425160 to your computer and use it in GitHub Desktop.
Subtle scala quirk with implicit conversions
@ "42".toInt
res0: Int = 42
@ implicit object Foo extends Function1[String, Int] {
def apply(s: String) = s.toInt
}
defined object Foo
@ "42”.toInt
// BOOM (infinite recursion)
@gabro
Copy link
Author

gabro commented Sep 4, 2015

Explanation: calling toInt (not defined on String) triggers an implicit lookup, which usually hits the toInt method defined on StringLike

Too bad that toInt is defined also on Int and we're providing an implicit function from String to Int, which has the precedence (it's "closer" in the scope) and uses toInt.

Result (after implicit expansion):

implicit object Foo extends Function1[String, Int] {
  def apply(s: String) = Foo.apply(s).toInt // <-- infinite recursion
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment