score:1
It seems like there is an extra complexity from a mix of different types of polymorphism in both examples. Here is a minimal example of just a type class:
// type class itself
trait JsonParser[T] {
def parse(payload: String): Try[T]
}
// type class instances
object JsonParserInstances {
implicit val type1Parser: JsonParser[Type1] = new JsonParser[Type1] {
def parse(payload: String): Try[Type1] = ???
}
implicit val type2Parser: JsonParser[Type2] = new JsonParser[Type2] {
def parse(payload: String): Try[Type2] = ???
}
}
// type class interface
object JsonInterface {
def parse[T](payload: String)(implicit T: JsonParser[T]): Try[T] = {
T.parse(payload)
}
}
def main(args: Array[String]): Unit = {
import JsonParserInstances._
JsonInterface.parse[Type1]("3")
JsonInterface.parse[Type2]("3")
}
More info:
- Chapter on Typeclasses in free Scala with Cats Book
score:4
As I've already tried to explain in the comments, the problem is that the method
override def parse[T](payload: String): Try[T] = parseInternal(payload)
does not accept any JsonParserLike[T]
instances. Therefore, the compiler has no way to insert the right instance of JsonParserLike[T]
at the call site (where the type T
is known).
To make it work, one would have to add some kind of token that uniquely identifies type T
to the argument list of parse
. One crude way would be to add a JsonParserLike[T]
itself:
import util.Try
trait Parser {
def parse[T: JsonParserLike](payload : String) : Try[T]
}
class JsonParser extends Parser {
override def parse[T: JsonParserLike](payload: String): Try[T] =
parseInternal(payload)
private def parseInternal[T:JsonParserLike](payload:String):Try[T] = {
implicitly[JsonParserLike[T]].parse(payload)
}
}
trait JsonParserLike[T] {
def parse(payload: String): Try[T]
}
object JsonParserLike {
implicit val type1Parser: JsonParserLike[String] = ???
implicit val type2Parser: JsonParserLike[Int] = ???
}
Now it compiles, because the JsonParserLike[T]
required by parseInternal
is inserted automatically as an implicit parameter to parse
.
This might be not exactly what you want, because it creates a hard dependency between Parser
interface and the JsonParserLike
typeclass. You might want to get some inspiration from something like shapeless.Typeable to get rid of the JsonParserLike
in the Parser
interface, or just rely on circe right away.
Source: stackoverflow.com
Related Query
- Ambiguous implicit values for Typeclass
- Play 2.2.1: ambiguous implicit values for object PlayMagicForJava
- Ambiguous Implicit Values for Case Class Option Parameter
- Ambiguous implicit values
- scala cats ambiguous implicit values
- Scala multiple implicit parameters with defaults resulting in ambiguous values
- Slick 3.1.1 ambiguous implicit values involving filter and implicit CanBeQueryCondition
- play json writes subclass gives ambiguous implicit values error
- Scala generic implicit values ambiguous when overloading?
- Why in-scope implicit values typed A and B are not ambiguous when B extends A?
- Resolving Implicit for `Show` Typeclass Instance
- Default implicit object/definition for a typeclass
- Use different implicit values for same type
- Implicit lookup for Typeclass of None is not compatible with Contravariant Typeclass of Option
- ambiguous implicit values in scala-redis connector
- Scala typeclass for providing an instance either from derivation or from an existing implicit value
- Implicit values of generic types for implicit parameters in scala
- Typeclass ops : Enable to find implicit value for parameter
- Use implicit typeclass parameter for default argument
- Scala trait: How to require output parameter to be Numeric: ambiguous implicit values error
- Ambiguous Implicit Values when using HMap
- ambiguous implicit values when using contravariant generic type
- Kafka Streams: SessionWindowedSerde Vs TimeWindowedSerde. Ambiguous implicit values
- ReactiveMongo findOne gives ambiguous implicit values
- Implicit method for typeclass not found
- Play 2.4: Form: could not find implicit value for parameter messages: play.api.i18n.Messages
- Filter map for values of None
- Is there a way to declare an implicit val inside a for comprehension?
- Why implicitConversions is required for implicit defs but not classes?
- Log implicits only for "diverging implicit expansion"s
More Query from same tag
- scala generic method overriding
- Understanding why "pimp my library" was defined that way in Scala
- How can I better collect multiple validation errors when attempting to instantiate a case class
- Scala WindowFunction does not compile
- How to generate avro ocf format(with schema) data/file using scala?
- How to set StorageLevel.MEMORY_AND_DISK_SER for KafkaUtils.createDirectStream?
- Scala semantics of equals/hashCode for case classes with traits
- LIFT: preventing orphaned records when destroying an object
- Structural type in method type parameterization in Scala?
- Would scala close the InputStream automatically?
- Spark Standalone Mode: Connection to 127.0.1.1:<PORT> refused
- tuple values for a key in scala rdd
- Scala / Slick 3.0.1 - Update Multiple Columns
- Scala: Can a code block be converted to a closure?
- How are primitives types objects in Scala?
- HiveContext - unable to access hbase table mapped in hive as external table
- Starting Node server from Scala app with environment variables
- how to iterate on a JsObject and insert a new fields for each object? (play framwork)
- How to run code on startup in Play! framework 2.4
- Are functions with Try/Option signature a pure function?
- How to properly construct a Twitter Future
- while running console from SBT getting error "Couldn't retrieve source module: org.scala-sbt:compiler-interface:0.13.13:component"
- How to instantiate a Java generic inner class in Scala?
- How to compile and run scala code quickly in vim?
- how to make scalatest work with spraytestkit and HttpServiceActor
- Orderings and TreeMap
- Interactive debug console for scala in Intellij?
- Is there a more functional way to do this sequence of requests?
- Finagle + Thrift: Count method invocations
- Map null values to None in Scala using Circe