Created
December 21, 2018 14:38
-
-
Save mpilquist/7b9288f65050a880bdaa30c14ae2b5f7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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