java - Issue with HashMap ordering on generic type in Scala -


this simplified code explain happens. there different type of column classes 1 here intcolumn. there shortcolumn, longcolumn etc. getmin processing on values file , needs return min value. value type depends on column type.

abstract class column[a] {     val name: string     val size: int     def stringtovalue(s: string): }  case class intcolumn(name: string) extends column[int] {     val size = 4     def stringtovalue(s: string): int = s.toint }  val col = intcolumn("id")  import scala.collection.mutable.hashmap  def getmin[a](col: column[a]): (a, int) = {     val hm = hashmap[a, int]()      // process data csv file...      hm.put(col.stringtovalue("1"), 1)     hm.put(col.stringtovalue("2"), 1)     hm.put(col.stringtovalue("3"), 1)      hm.min // min hashmap item }  val min = getmin(col) // expecting (1, 1) of type (int, int) 

when executing getmin error below. thought compiler here has enough information figure out , able compare values in hashmap.

error:(21, 9) no implicit ordering defined (a, int).     hm.min        ^ error:(21, 9) not enough arguments method min: (implicit cmp: ordering[(a, int)])(a, int). unspecified value parameter cmp.     hm.min        ^ 

at point of hm.min call compiler has knowledge key of hash map abstract type a. doesn't automatically keep track of implicits associated abstract types.

there 2 ways solve this:

  1. either change definition of getmin take implicit ordering:

    def getmin[a: ordering](col: column[a]): (a, int) 

    at point of getmin call compiler knows argument has concrete type column[int]. able figure out implicit ordering , pass getmin.

  2. or make column hold ordering content type:

    abstract class column[a](implicit val ord: ordering[a]) 

    the ordering provided , stored column creation val col = intcolumn("id")

    you have make ordering available hm.min importing in getmin:

    def getmin[a](col: column[a]): (a, int) = {   import col.ord   // ... else stays same 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -