I was trying to workout the classic example of converting arbitrary values into their Json representation and having compile time errors in case conversion is not defined.
So far, I have,
trait Json
trait ConvertableToJson[A] {
def toJson: Json
}
object Json {
case class Str(str: String) extends Json
case class Int(int : Int) extends Json
case class StrToJson(s: String) extends ConvertableToJson[StrToJson] {
override def toJson: Json = Str(s)
}
}
implicit def str2Json(s: String): StrToJson = StrToJson(s)
def toJson[A <: ConvertableToJson[A]](a: A) = a.toJson
println(toJson("some string"))
I expected the above code to work like:
toJson("some string") to fail to compile without the implicit def. Because String <: ConvertableToJson[String] is false.
But then to use, the implicit def and find Str2Json.
Str2Json <: ConvertableToJson[Str2Json] should be true.
However, this doesn't happen and compiler complains:
Error: Inferred type arguments [String] do not conform to method toJson's type parameter bounds [A <: scalaz.ConvertToJson.ConvertableToJson[A]]
println(toJson("dhruv"))
^
It'll be great if someone can help me correct my understanding
So there are two problems with your code. First of all String does not extend ConvertableToJson[String], which is what your last function call is trying to do.
Second case class StrToJson should extend ConvertableToJson[String] not ConvertableToJson[StrToJson].
Then your code be made to compile by using view-bounds <% (see the working example below). This however is a bad idea because view-bounds are being deprecated as a language feature, you should use type classes instead.
trait Json
trait ConvertableToJson[A] {
def toJson: Json
}
object Json {
case class Str(str: String) extends Json
case class Int(int : Int) extends Json
case class StrToJson(s: String) extends ConvertableToJson[String] {
override def toJson: Json = Str(s)
}
}
import Json._
implicit def str2Json(s: String): StrToJson = StrToJson(s)
def toJson[A <% ConvertableToJson[A]](a: A) = a.toJson
println(toJson("some string"))
Using typeclasses
trait Json
trait ConvertableToJson[A] {
// NOTE: this now takes a parameter
def toJson(a: A): Json
}
object Json {
case class Str(str: String) extends Json
case class Int(int : Int) extends Json
}
import Json._
// NOTE: Because toJson takes a parameter the implicit implementation can now be an object
implicit object Str2Json extends ConvertableToJson[String] {
override def toJson(a: String): Json = Str(a)
}
// NOTE: If you want to support the a.toJson syntax this implicit class adds it for all types with an implicit ConvertableToJson
implicit class ConvertableToJsonSyntax[A](a: A)(implicit ev: ConvertableToJson[A]) {
def toJson: Json = ev.toJson(a)
}
// NOTE: Now we use context-bounds instead of view-bounds
def toJson[A : ConvertableToJson](a: A) = a.toJson
// NOTE: we can expand the context-bounds
def toJson2[A](a: A)(implicit ev: ConvertableToJson[A]) = a.toJson
// NOTE: But since we have the type class instance now, we do not need the extra syntax
def toJson3[A](a: A)(implicit ev: ConvertableToJson[A]) = ev.toJson(a)
println(toJson("some string"))
Related
I don't get the following code to compile and I am curious of what I did wrong.
I defined a Contravariant Jsonwriter Trait and a function accepting implicit writers:
trait JsonWriter[-A] {
def write(value: A): Json
}
object Json {
def toJson[A](value: A)(implicit writer: JsonWriter[A]): Json =
writer.write(value)
}
Additionally I have defined some instances of these writers:
object JsonWriterInstances {
implicit val stringWriter: JsonWriter[String] =
(value: String) => JsString(value)
implicit val doubleWriter: JsonWriter[Double] =
(value: Double) => JsNumber(value)
class OptionWriter[-T](writer: JsonWriter[T]) extends JsonWriter[Option[T]] {
def write(value: Option[T]): Json = {
value match {
case None => JsNull
case Some(x) => writer.write(x)
}
}
}
implicit def optionWriter[T](implicit writer: JsonWriter[T]):
JsonWriter[Option[T]] = new OptionWriter[T](writer)
}
Now I have written a test:
"write double Option" in {
Some(1.0).toJson should be(JsNumber(1.0))
None.toJson should be(JsNull)
}
The first test for Some(1.0) works fine
The second one for None throws:
Error:(40, 12) could not find implicit value for parameter writer: JsonWriter[None.type]
None.toJson should be(JsNull)
If you want to try the code my JsonType definitions for this example are:
sealed trait Json
final case class JsObject(get: Map[String, Json]) extends Json
final case class JsString(get: String) extends Json
final case class JsNumber(get: Double) extends Json
case object JsNull extends Json
None, if you dont say anything else, is a Option[Nothing], so OptionWriter[Nothing] needs a JsonWriter[Nothing]. If you try Json.toJson(Some(1)) is the same, there is no JsonWriter[Int].
On the other hand, Json.toJson(None:Option[String]) works, because OptionWriter[String] can get a JsonWriter[String].
I think it has to do with the fact that
case object None extends Option[Nothing] { ... }
if you do one of the following, it will work
toJson(Option.empty[Double])
toJson(None : Option[Double])
Note that the second one uses type ascription to put a face, so to speak, on the Nothing (which is a subtype of everything)
I have a trait for which I wanted to write Typeclasses for. This trait actually is a contract to do JSON to Case class conversion and vice versa. The definition of the trait is as below:
trait Converter[T] {
def convertFromJson(msg: String): Either[ConverterError, T]
def convertToJson(msg: T): String
}
Now, for one of the case classes that I have, I have defined the implementation like this:
object Converter extends DefaultJsonProtocol {
implicit object DefaultMessageConversions extends Converter[DefaultMessage] {
implicit val json = jsonFormat(DefaultMessage, "timestamp")
def convertFromJson(msg: String): Either[ConverterError, DefaultMessage] = {
try {
Right(msg.parseJson.convertTo[DefaultMessage])
}
catch {
case _: Exception => Left(ConverterError("Shit happens"))
}
}
def convertToJson(msg: DefaultMessage) = {
implicit val writes = Json.writes[DefaultMessage]
Json.toJson(msg).toString
}
}
def apply[T: Converter] : Converter[T] = implicitly
}
But I run into some compiler errors when I tried to build my project. I'm not sure what I did wrong?
[error] /Users/joesan/ingestion/src/main/scala/com/my/project/common/JsonMessageConversion.scala:28: could not find implicit value for evidence parameter of type com.my.project.common.JsonMessageConversion.Converter.JF[org.joda.time.DateTime]
[error] implicit val json = jsonFormat(DefaultMessage, "timestamp")
Here is how my case class look like:
case class DefaultMessage(timestamp: DateTime) extends KafkaMessage {
def this() = this(DateTime.now(DateTimeZone.UTC))
}
Your DefaultMessage uses org.joda.time.DateTime and spray-json does not know how to serialize/deserialize it out of the box.
Therefore you need to define a RootJsonFormat[DateTime] and bring it in implicit scope.
Here is an example implementation.
Let's say we have the following traits:
trait MyValue
object MyValue {
case class MyBoolean(record: Boolean) extends MyValue
case class MyLong(record: Long) extends MyValue
}
trait MyValueExtractor[T] {
def apply(record: T): Option[MyValue]
}
trait MyThing[T] {
def name: String
def myValueExtractor: MyValueExtractor[T]
def myValue(record: T): Option[MyValue] = myValueExtractor(record)
}
What I want is something like this but without the second type parameter.
Note: I can't actually update the MyThing trait; I'm just using this as an illustration of the intended functionality.
trait MyThing[T, U] {
def name: String
def myValueExtractor: MyValueExtractor[T]
def myValue(record: T): Option[MyValue] = myValueExtractor(record)
def myRelatedValue(record: T): Option[U]
}
I'm wondering if I could use the type class pattern to help solve this (i.e., import some rich class that implicitly gives me a myRelatedValue method)?
Here's the rub. Every time T (above) is MyValue.MyBoolean, U must be a String. Every time T is MyValue.MyLong, U must be a Double. In other words, there's a sort of underlying mapping between T and U.
Is there a good way to do this using type class?
Sure. You just need to define some Mapping typeclass with implementations for your desired pairs of types. Then MyThing can have a method that takes an implicit typeclass instance and simply invokes its method.
Here's the code (I removed the unneeded details)
// types
case class MyBoolean(record: Boolean)
case class MyLong(record: Long)
// trait which uses the Mapping typeclass
trait MyThing[T] {
def myRelatedValue[U](record: T)(implicit ev: Mapping[T, U]): Option[U] = ev.relatedValue(record)
}
// typeclass itself
trait Mapping[T, U] {
def relatedValue(record: T): Option[U]
}
object Mapping {
implicit val boolStringMapping = new Mapping[MyBoolean, String] {
def relatedValue(record: MyBoolean) = Some(record.record.toString)
}
implicit val longDoubleMapping = new Mapping[MyLong, Double] {
def relatedValue(record: MyLong) = Some(record.record)
}
}
// usage
val myBoolThing = new MyThing[MyBoolean] {}
val myLongThing = new MyThing[MyLong] {}
val myStringThing = new MyThing[String] {}
myBoolThing.myRelatedValue(MyBoolean(true)) // Some(true)
myLongThing.myRelatedValue(MyLong(42L)) // Some(42.0)
myStringThing.myRelatedValue("someString") // error: could not find implicit value
Note that e.g. myBoolThing.myRelatedValue(MyBoolean(true)) will yield a type Option[U]. However, since myRelatedValue is parameterized, you can help the compiler and invoke it as myBoolThing.myRelatedValue[String](MyBoolean(true)), in which case you will obtain an Option[String]. If you try something other than String for MyBoolean, you will get an error.
Some setup before my question:
/* roughly equivalent to a union type */
sealed trait NewType
object NewType {
final case class Boolean(record: Boolean) extends NewType
final case class Long(record: Long) extends NewType
final case class String(record: String) extends NewType
}
/* Try to convert a record of type T to a NewType */
sealed trait NewTypeConverter[T] { def apply(record: T): Option[NewType] }
object NewTypeConverter {
trait BooleanConverter[T] extends NewTypeConverter[T] {
override def apply(record: T): Option[NewType.Boolean]
}
trait LongConverter[T] extends NewTypeConverter[T] {
override def apply(record: T): Option[NewType.Long]
}
trait StringConverter[T] extends NewTypeConverter[T] {
override def apply(record: T): Option[NewType.String]
}
}
I want to define a trait Data like the following:
trait Data[T] {
def name: String
def converter: NewTypeConverter[_]
final def value(record: T): Option[NewType] = ??? // calls converter
}
How can I implement this final def value(record: T): Option[NewType]?
A few things to note:
The return type from the apply method of converter must be the same return type as value. So, if you happen to have a BooleanConverter, then value must return an Option[NewValue.Boolean].
Input type T to the Data trait does not have to be the same as the input type _ to the converter. If they happen to be the same type, then the implementation could just be final def value(record: T): Option[NewType] = converter(record). The trickier case is in when the input types differ. Let's say the input type to Data was a String, but the input type to converter was a Long. How would that be handled?
It looks like you are 90% through implementing the Type Class pattern, so I'll try to solve your issue by completing it. Here is a nice reading about it. In short, what you miss is a signature that states that, if one (and only one) implementation of the converter can be found in the implicit scope, use it to run the conversion (or anything else defined by the trait).
The signature is the following:
final def value(record: T)(implicit c: NewTypeConverter[T]): Option[NewType]
Given such a strict signature also makes the implementation quite straightforward:
final def value(record: T)(implicit c: NewTypeConverter[T]): Option[NewType] =
c(record) // literally only applies `c`, the converter
Now, whenever you have your converter instance in the implicit scope, for example the following:
implicit val converter: NewTypeConverter[Boolean] =
new StringConverter[Boolean] {
override def apply(record: Boolean): Option[NewType.String] =
if (record) Some(NewType.String("TRUE"))
else Some(NewType.String("FALSE"))
}
you can instance your trait (simplified in the example):
trait Data[T] {
def name: String
final def value(record: T)(implicit c: NewTypeConverter[T]): Option[NewType] =
c(record)
}
final case class BooleanData(name: String) extends Data[Boolean]
val bool = BooleanData(name = "foo")
And use it:
println(bool.value(true)) // prints Some(String(TRUE))
println(bool.value(false)) // prints Some(String(FALSE))
If you try to invoke the value method from a place where you have no access to the implicit instance you'll get an error:
error: could not find implicit value for parameter converter: NewTypeConverter[Boolean]
Bonus
Providing evidence for a known capability of an object via implicits is so common that Scala has some syntactic sugar you can use if you need to provide such evidence (for example, you have a method that calls your value method) but you do not have to use it directly. It's expressed as follows, with the : right after the generic type:
def methodThatCallsValue[T: Data](convertee: T): Option[NewType] =
data.value(convertee)
it's called context bound and is equivalent to the following (which was done explicitly in the example):
def methodThatCallsValue(convertee: T)(implicit $ev: Data[T]): Option[NewType] =
data.value(convertee)
my classes look like this
trait Value[T] {
def get:T
}
I have implementations of this, for example
class StringValue(value : String) extends Value[String] {
override def get : String = value
}
class NumberValue(value : Int) extends Value[Int] {
override def get: Int = value
}
The problem is that I need to make jsonFormat for this types in order to save it to MongoDB.
I stucked for two days but still cannot figure out how to make it work
As for the provided .nullable which returns Reads for Option (generic type), you need to first enforce that the type parameter of Value is itself provided the required instances of Reads and Writes.
So for a generic Reads[Value[T]] the minimal def would be as bellow.
def valueReads[T](implicit underlying: Reads[T]): Reads[Value[T]] = ???
Similarily, for Writes[Value[T]] (or OWrites if it needs to be restricted to JSON object, and thus BSON document), the minimal definition would be as following.
def valueWrites[T](implicit underlying: Writes[T]): Writes[Value[T]] = ???
// or
def valueOWrites[T](implicit underlying: Writes[T]): OWrites[Value[T]] = ??? // don't define both as implicit to avoid conflict
Then the implementation depends on the way you want to represent Value[T] as JSON.
Considering the following JSON representation:
{ "_value": ... }
... then the Reads would be something as bellow.
implicit def valueReads[T](implicit underlying: Reads[T]): Reads[Value[T]] =
Reads[Value[T]] { json =>
(json \ "_value").validate(underlying).map { t: T =>
Value(t)
}
}
Similarily, the OWrites[Value[T]] would be as following.
implicit def valueWrites[T](implicit underlying: Writes[T]): OWrites[Value[T]] =
OWrites[Value[T]] { value => Json.obj("_value" -> value) }
Obviously, these implicits need to be in the implicit scope, either by being defined in the Value companion object, or by being explicitly imported if defined elsewhere.