Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Fields, ADT, or?

Tags:

scala

Given an A, which may have optional fields, a and b:

case class A(a: Option[Int], b: Option[String])

I could define A as an Algebraic Data Type.

However, it would require 4 sub-classes to account for each None/Option choice:

sealed trait AADT
case class Aa(a: Int) extends AADT
case class Aab(a: Int, b: String) extends AADT
case class Ab(b: String) extends AADT
case object Neither extends AADT

I'd argue that this ADT is preferable to the above A option, which has Option types.

However, this type could quickly get out of hand with 3, 4, etc. fields.

Is there a third way to implement A, i.e. not using either my first or second implementation?

like image 495
Kevin Meredith Avatar asked Dec 05 '25 07:12

Kevin Meredith


1 Answers

Algebraically there is a third option that covers all combination

sealed trait A
case class Ao(o: Option[(Int, String)]) extends A //all or none
case class Ae(e: Either[Int, String]) extends A //first or second

I would definitely choose some sort of ADT if there is a separate domain name for each case.

Optional fields are good for data transferred objects (DTO)

like image 60
Nazarii Bardiuk Avatar answered Dec 08 '25 01:12

Nazarii Bardiuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!