Skip to content

Instantly share code, notes, and snippets.

@longliveenduro
Last active April 22, 2022 10:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save longliveenduro/62638ec95a6fd0c6576bdb77ca88cd6b to your computer and use it in GitHub Desktop.
Save longliveenduro/62638ec95a6fd0c6576bdb77ca88cd6b to your computer and use it in GitHub Desktop.
import scala.util.Try
/**
* Alternative to unsound construct: "sealed abstract case class"
* see https://gist.github.com/tpolecat/a5cb0dc9adeacc93f846835ed21c92d2
* The solution below is the summary of the comments of the above gist.
*
* Works as is in Scala 2.12 and higher
* In Scala 2.11.12 you have to add -Xsource:2.12
*/
final case class NotWeird private (field: Int) {
// if you really want one (e.g. for lenses)
def copy(field: Int = field) = NotWeird(field)
}
object NotWeird {
def apply(field: Int): NotWeird = {
if (field > 0) new NotWeird(field)
else throw new IllegalArgumentException("Only positive numbers")
}
}
object TryItOut extends App {
// does not compile
// println("new NotWeird(3): " + new NotWeird(3))
println("NotWeird(3): " + NotWeird(3))
println("Try(NotWeird(-3)): " + Try(NotWeird(-3)))
println("NotWeird(3).copy(field = 1): " + NotWeird(3).copy(field = 1))
println("Try(NotWeird(3).copy(-5)): " + Try(NotWeird(3).copy(-5)))
}
@longliveenduro
Copy link
Author

longliveenduro commented Jul 22, 2020

SBT file for 2.11 with compiler flag:

`
name := "CaseClass"

version := "0.1"

scalaVersion := "2.11.12"

scalacOptions ++= Seq("-Xsource:2.12")
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment