Permalink
Browse files

#505 Primitive classes should be handled specially

  • Loading branch information...
1 parent e2620f9 commit e7a11e1cd5ac3f020d8c225b3eae43b8c6e9e14d @ngocdaothanh ngocdaothanh committed Mar 13, 2015
Showing with 52 additions and 4 deletions.
  1. +22 −4 src/main/scala/xitrum/OptVar.scala
  2. +30 −0 src/test/scala/xitrum/OptVarPrimitiveTest.scala
@@ -35,11 +35,29 @@ abstract class OptVar[+A](implicit m: Manifest[A]) {
* which is worse than the ClassCastException.
*/
private def clearAllOnClassCastException(a: Any)(implicit action: Action) {
- val classOfA = m.runtimeClass
- if (!classOfA.isInstance(a)) {
- action.log.warn(s"Value $a of key $key can't be cast to $classOfA, $this is now cleared to try to recover from ClassCastException on next call")
+ val rClass = m.runtimeClass
+
+ // http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isPrimitive()
+ // http://stackoverflow.com/questions/16825927/classtag-based-pattern-matching-fails-for-primitives
+ val rightClass = if (rClass.isPrimitive) {
+ val aClass = a.getClass
+ (aClass == classOf[java.lang.Boolean] && rClass == java.lang.Boolean.TYPE) ||
+ (aClass == classOf[java.lang.Character] && rClass == java.lang.Character.TYPE) ||
+ (aClass == classOf[java.lang.Byte] && rClass == java.lang.Byte.TYPE) ||
+ (aClass == classOf[java.lang.Short] && rClass == java.lang.Short.TYPE) ||
+ (aClass == classOf[java.lang.Integer] && rClass == java.lang.Integer.TYPE) ||
+ (aClass == classOf[java.lang.Long] && rClass == java.lang.Long.TYPE) ||
+ (aClass == classOf[java.lang.Float] && rClass == java.lang.Float.TYPE) ||
+ (aClass == classOf[java.lang.Double] && rClass == java.lang.Double.TYPE) ||
+ (aClass == classOf[java.lang.Void] && rClass == java.lang.Void.TYPE)
+ } else {
+ rClass.isInstance(a)
+ }
+
+ if (!rightClass) {
+ action.log.warn(s"Value $a of key $key can't be cast to $rClass, $this is now cleared to try to recover from ClassCastException on next call")
getAll.clear()
- throw new ClassCastException(s"Value $a of key $key can't be cast to $classOfA")
+ throw new ClassCastException(s"Value $a of key $key can't be cast to $rClass")
}
}
@@ -0,0 +1,30 @@
+package xitrum
+
+import scala.collection.mutable.{Map => MMap}
+import org.scalatest.{FlatSpec, Matchers}
+
+class OptVarPrimitiveTest extends FlatSpec with Matchers {
+ behavior of "OptVarPrimitive"
+
+ implicit val action = new Action { def execute() {} }
+
+ def newOptVar() = new OptVar[Int] {
+ private val all = MMap[String, Any](key -> 123)
+ def getAll(implicit action: Action) = all
+ }
+
+ "get" should "handle primitive" in {
+ val v = newOptVar()
+ v.get shouldBe 123
+ }
+
+ "remove" should "handle primitive" in {
+ val v = newOptVar()
+ v.remove() shouldBe Some(123)
+ }
+
+ "toOption" should "handle primitive" in {
+ val v = newOptVar()
+ v.toOption shouldBe Some(123)
+ }
+}

0 comments on commit e7a11e1

Please sign in to comment.