Created
June 11, 2021 20:25
-
-
Save calvinlfer/f6d734659944e28bff90553b4f4390f1 to your computer and use it in GitHub Desktop.
Refined types in Scala 3 with ZIO Prelude
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.compiletime._ | |
import zio.prelude._ | |
package safer: | |
type Digit5OrMore = Digit5OrMore.Type | |
object Digit5OrMore extends Subtype[Int]: | |
private inline def check(i: Int): Boolean = i >= 5 | |
private inline def renderError(i: Int): String = s"input $i must be at least 5" | |
inline def compiletime(inline i: Int): Digit5OrMore = | |
inline if check(i) then Digit5OrMore(i) | |
else error(renderError(i)) | |
def runtime(i: Int): Either[String, Digit5OrMore] = | |
if check(i) then Right(Digit5OrMore(i)) | |
else Left(renderError(i)) | |
val compileTimeExample: Digit5OrMore = Digit5OrMore.compiletime(4) // compile time error | |
val runtimeExample: Either[String, Digit5OrMore] = Digit5OrMore.runtime(4). // Left("input 4 must be at least 5") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since opaque types have a limitation where they cannot be used with inline as of Scala 3.0.0, we make use of Newtype/Subtype