scalascala-generics

Scala generic wildcard and specific type


I have the mappings value:

val mappings: Map[Class[_] ,Iterable[AttributeKeyAndValue] => AnyRef]

is it possible to make it more typesafe like

val mappings: Map[Class[T], Iterable[AttributeKeyAndValue] => T]

where T plays the same role as underscore. I'd expect compiler to complain, if it meets this code:

val mappings: Map[Class[T], Iterable[AttributeKeyAndValue] => T] = Map(
  classOf[String], attrs => 1)

Solution

  • You can't parametrize vals so no, not like that.

    Looking at your request, it doesn't make much sense. Lets say that this: val mappings: Map[Class[T], Iterable[AttributeKeyAndValue] => T] was valid and the compiler would complain.

    You would either parametrize all the entries in the map with the same type, ie. T or have each entry with it's own parametrized type making it impossible to know which type it is when retrieving the entries with the apply or get methods.

    I suggest you stick with the Class[_] because the only way to parametrize this is to force all the entries to have the same type. For example if you were able to parametrize it in Map[Class[String], ...] then you would only be able to put 1 entry in the map, the one where the key is classOf[String]