Last active
August 29, 2015 14:13
-
-
Save jyemin/393891632df6de1513ab to your computer and use it in GitHub Desktop.
Class Cast Hell
This file contains 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
var doc = new BsonDocument("x", 10.0); | |
var x1 = doc["x"].AsInt32; // breaks | |
var x2 = (int)doc["x"]; // breaks | |
var x3 = doc["x"].ToInt32(); // ok |
This file contains 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
collection.createIndex(new BasicDBObject("x", 1)); // covering index | |
collection.insert(new BasicDBObject("x", 1)); | |
collection.insert(new BasicDBObject("x", 2)); | |
collection.insert(new BasicDBObject("x", 3)); | |
DBObject doc = collection.findOne(new BasicDBObject("x", new BasicDBObject("$lt", 3)), // query | |
new BasicDBObject("x", 1).append("_id", 0)); // projection | |
int x = ((Number) doc.get(("x"))).intValue(); // a safe but probably rarely used workaround | |
x = (Integer) doc.get(("x")); // but this will blow up with a ClassCastException | |
This file contains 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
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment