Skip to content

Instantly share code, notes, and snippets.

@mpilquist
Created December 21, 2018 14:38
Show Gist options
  • Save mpilquist/7b9288f65050a880bdaa30c14ae2b5f7 to your computer and use it in GitHub Desktop.
Save mpilquist/7b9288f65050a880bdaa30c14ae2b5f7 to your computer and use it in GitHub Desktop.
// Alternative to sealed abstract case class pattern for Scala 2.12.2+
// Benefits:
// - 1 final class instead of 1 sealed class + anonymous subclass
// - portable to Scala 3 regardless of opaque types
// - less boilerplate
final case class Angle private (toDegrees: Int) {
// Define our own `copy` method to suppress synthetic one
// Add private to prevent it from being used
def copy(degrees: Int = toDegrees): Angle = Angle.fromDegrees(degrees)
}
object Angle {
// Define our own `apply` method to suppress synthetic one
// Can keep this public if you want Angle(-32) to work
private def apply(n: Int): Angle = new Angle(((n % 360) + 360) % 360)
def fromDegrees(n: Int): Angle = apply(n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment