Skip to content

Instantly share code, notes, and snippets.

@joescii
Created October 23, 2014 20:42
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 joescii/552efbcfd3d43eaad4ba to your computer and use it in GitHub Desktop.
Save joescii/552efbcfd3d43eaad4ba to your computer and use it in GitHub Desktop.
The good, bad, and ugly of implicits with +
package com.joescii
import org.scalatest.{ShouldMatchers, FlatSpecLike}
/**
* Created by jbarnes on 10/23/2014.
*/
class ImplicitSpecs extends FlatSpecLike with ShouldMatchers {
"Scala implicits" should "act like their java counterparts" in {
val java = new MyJavaClass
java.a should equal (1 + "1")
java.b should equal (1 + 1 + "1")
java.c should equal ("1" + 1 + 1)
java.d should equal (1 + "1" + 1)
}
}
package com.joescii;
/**
* Created by jbarnes on 1/24/14.
*/
public class MyJavaClass {
public String a = 1 + "1";
public String b = 1 + 1 + "1";
public String c = "1" + 1 + 1;
public String d = 1 + "1" + 1;
}
@joescii
Copy link
Author

joescii commented Oct 23, 2014

After a second look at your original tweet, I realize my reply was dumb. I didn't see all of the examples thanks to the hootsuite twitter client on my iPhone. 👎

So only "1" + 1 + 1 is java-interop (which is the only one I saw originally). This is because Scala wholly reuses java.lang.String, which has a + defined accepting any java.lang.Object, and hence Any from Scala.

As for the others.... yes, they are implicit conversions (facepalm). I agree on the principle that you dislike it, but I also get that the + is not consistent across the four examples. Scala's approach is also consistent with Java, which is an awfully heavy influence on the language.

Ok, so I did a dumb, but hopefully this explanation is still helpful for you. :)

@johnazariah
Copy link

Thanks for taking the time to do this - appreciate it!

The problem is exactly that Scala values (consistency with Java) more than (strict strong-typing) :)

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