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:
either change definition of
getmintake implicitordering:def getmin[a: ordering](col: column[a]): (a, int)at point of
getmincall compiler knows argument has concrete typecolumn[int]. able figure out implicitordering, passgetmin.or make
columnholdorderingcontent type:abstract class column[a](implicit val ord: ordering[a])the
orderingprovided , stored column creationval col = intcolumn("id")you have make
orderingavailablehm.minimporting ingetmin:def getmin[a](col: column[a]): (a, int) = { import col.ord // ... else stays same
Comments
Post a Comment