Eran Medan
Eran Medan

Reputation: 45765

Is there a way to avoid repeating the type parameters when using a trait?

Consider this code

val map = new HashMap[(String, String), Set[(String, Int, Double, Int)]] 
        with MultiMap[(String, String),     (String, Int, Double, Int)]

Is there a way to use the Multimap trait without repeating the type parameters definition?

Upvotes: 2

Views: 183

Answers (1)

oxbow_lakes
oxbow_lakes

Reputation: 134310

You can use a type alias to cut down on repetition

type K = (String, String)
type V = (String, Int, Double, Int)

Then your map becomes

val map = new HashMap[K, Set[V]] with MultiMap[K, V]

However, as a stylistic rule I don't find it a good idea to use the TupleN traits so much in code for a few reasons:

  • they are harder to refactor (e.g. if you need an extra field)
  • it is less obvious what they represent

Considering that the overhead of creating a bespoke class is as little as:

case class K(p1: String, p2: String)

it's usually worth it!

Upvotes: 8

Related Questions