Created
October 23, 2014 20:42
-
-
Save joescii/552efbcfd3d43eaad4ba to your computer and use it in GitHub Desktop.
The good, bad, and ugly of implicits with +
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
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 anyjava.lang.Object
, and henceAny
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. :)