Last active
April 22, 2022 10:00
-
-
Save longliveenduro/62638ec95a6fd0c6576bdb77ca88cd6b 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
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))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SBT file for 2.11 with compiler flag:
`
name := "CaseClass"
version := "0.1"
scalaVersion := "2.11.12"
scalacOptions ++= Seq("-Xsource:2.12")
`