How to create a typeclass instance for any subclass of Traversable in Scala -
i've created toy example illustrate compiler error don't understand. shouldn't implicit conversion c[_] <: traversable[t]
safe[t]
safe[c[t]]
apply?
import scala.language.{implicitconversions, higherkinds} class toyexample { implicit val stringsafe = new safe[string] { override def stringify(value: string): string = value } def main(args: array[string]): unit = { val a: string = "c" val b: seq[string] = seq("1", "2", "3") safe(a) safe(b) // why compiler error? } def safe[t](value: t)(implicit safe: safe[t]): string = safe stringify value } object safe { implicit def safetraversable[c[_] <: traversable[t], t](implicit safe: safe[t]): safe[c[t]] = new safe[c[t]] { override def stringify(value: c[t]): string = value.map(safe.stringify).tostring() } } trait safe[t] { def stringify(value: t): string }
ok, figured out how code compile, don't understand reason.
by modifying implicit conversion remove higher-kinded placeholder, able compile:
implicit def safetraversable[c <: traversable[t], t](implicit safe: safe[t]): safe[c] = new safe[c] { override def stringify(value: c): string = value.map(safe.stringify).tostring() }
does understand why higher kinded type invalid?
Comments
Post a Comment