Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an error where options of sealed traits weren't encoded correctly #238

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ class SealedTraitEncoderTest extends FunSuite with Matchers {
Encoder[Dibble].encode(Dobble, schema) shouldBe new GenericData.EnumSymbol(schema, Dobble)
Encoder[Dibble].encode(Dabble, schema) shouldBe new GenericData.EnumSymbol(schema, Dabble)
}

test("options of sealed traits should be encoded correctly") {
val schema = AvroSchema[MeasurableThing]
val record = Encoder[MeasurableThing].encode(MeasurableThing(Some(WidthDimension(1.23))), schema).asInstanceOf[GenericRecord]
val width = record.get("dimension").asInstanceOf[GenericRecord]
width.get("width") shouldBe 1.23
}
}

sealed trait Dibble
Expand All @@ -75,3 +82,9 @@ sealed trait Nibble
case class Nobble(str: String, place: String) extends Nibble
case class Nabble(str: String, age: Int) extends Nibble
case class Napper(nibble: Nibble)

sealed trait Dimension
case class HeightDimension(height: Double) extends Dimension
case class WidthDimension(width: Double) extends Dimension
case class MeasurableThing(dimension: Option[Dimension])

12 changes: 9 additions & 3 deletions avro4s-macros/src/main/scala/com/sksamuel/avro4s/Encoder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,15 @@ object Encoder extends CoproductEncoders with TupleEncoders {
import scala.collection.JavaConverters._

override def encode(t: Option[T], schema: Schema): AnyRef = {
// if the option is none we just return null, otherwise we encode the value
// by finding the non null schema
val nonNullSchema = schema.getTypes.asScala.find(_.getType != Schema.Type.NULL).get
val nonNullSchema = schema.getTypes().size match {
// if the option is none we just return null, otherwise we encode the value
// by finding the non null schema
case 2 => schema.getTypes.asScala.find(_.getType != Schema.Type.NULL).get
case otherwise => {
val remainingSchemas = schema.getTypes.asScala.filter(_.getType != Schema.Type.NULL)
Schema.createUnion(remainingSchemas.toList.asJava)
}
}
t.map(encoder.encode(_, nonNullSchema)).orNull
}
}
Expand Down