How to pattern match on generic type in Scala?

Maybe this will help def matchContainer[A: Manifest](c: Container[A]) = c match { case c: Container[String] if manifest <:< manifest[String] => println(c.value.toUpperCase) case c: Container[Double] if manifest <:< manifest[Double] => println(math.sqrt(c.value)) case c: Container[_] => println(“other”) } Edit: As Impredicative pointed out, Manifest is deprecated. Instead you could do the following: import reflect.runtime.universe._ def matchContainer[A: TypeTag](c: … Read more

What type erasure techniques are there, and how do they work?

All type erasure techniques in C++ are done with function pointers (for behaviour) and void* (for data). The “different” methods simply differ in the way they add semantic sugar. Virtual functions, e.g., are just semantic sugar for struct Class { struct vtable { void (*dtor)(Class*); void (*func)(Class*,double); } * vtbl }; iow: function pointers. That … Read more

Jackson JsonNode to typed Collection

Acquire an ObjectReader with ObjectMapper#readerFor(TypeReference) using a TypeReference describing the typed collection you want. Then use ObjectReader#readValue(JsonNode) to parse the JsonNode (presumably an ArrayNode). For example, to get a List<String> out of a JSON array containing only JSON strings ObjectMapper mapper = new ObjectMapper(); // example JsonNode JsonNode arrayNode = mapper.createArrayNode().add(“one”).add(“two”); // acquire reader for … Read more

Type erasure, overriding and generics

The signature of fooMethod(Class<?>) is the same as the signature of fooMethod(Class) after erasure, since the erasure of Class<?> is simply Class (JLS 4.6). Hence, fooMethod(Class) is a subsignature of the fooMethod(Class<?>) but not the opposite (JLS 8.4.2). For overriding with instance methods you need the overriding method to be a subsignature of the overridden … Read more

Serializing Map with Jackson

The default map key serializer is StdKeySerializer, and it simply does this. String keyStr = (value.getClass() == String.class) ? ((String) value) : value.toString(); jgen.writeFieldName(keyStr); You could make use of the SimpleModule feature, and specify a custom key serializer, using the addKeySerializer method. And here’s how that could be done. import java.io.IOException; import java.util.Date; import java.util.HashMap; … Read more

Why following types are reifiable& non-reifiable in java?

Sun/Oracle says the reason is combo of: Need: compile time type checking is sufficient Code size: avoid STL-like code bloat Performance: avoid type checking at runtime that was already done at compile Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead. In short, 1-5 are reifiable … Read more