Skip to content

Commit

Permalink
Close #30 - Extract the essential properties of Refined and create …
Browse files Browse the repository at this point in the history
…`RefinedBase`
  • Loading branch information
kevin-lee committed Aug 13, 2023
1 parent 3270cb2 commit 7ce3268
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 27 deletions.
Original file line number Diff line number Diff line change
@@ -1,37 +1,15 @@
package refined4s

import compiletime.*

/** Copied from https://gist.github.com/Kevin-Lee/158d3d5c3e036560f8962087a34c95c5 and modified.
* @author Kevin Lee
* @since 2022-03-23
*/
trait Refined[A] {
import compiletime.*

opaque type Type = A

given newRefinedCanEqual: CanEqual[Type, Type] = CanEqual.derived
trait Refined[A] extends RefinedBase[A] {

inline def apply(a: A): Type =
inline if predicate(a) then a else error("Invalid value: [" + codeOf(a) + "]. " + invalidReason(a))

def unapply(typ: Type): Option[A] = Some(typ)

@SuppressWarnings(Array("org.wartremover.warts.ToString"))
def from(a: A): Either[String, Type] =
if predicate(a) then Right(a) else Left("Invalid value: [" + a.toString + "]. " + invalidReason(a))

@SuppressWarnings(Array("org.wartremover.warts.Throw"))
def unsafeFrom(a: A): Type =
from(a).fold(err => throw new IllegalArgumentException(err), identity) // scalafix:ok DisableSyntax.throw

inline def expectedMessage(expected: String): String =
"It must be " + expected

def invalidReason(a: A): String

def predicate(a: A): Boolean
inline if predicate(a) then a.asInstanceOf[Type]
else error("Invalid value: [" + codeOf(a) + "]. " + invalidReason(a))

extension (typ: Type) {
inline def value: A = typ
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package refined4s

/** Copied from https://gist.github.com/Kevin-Lee/158d3d5c3e036560f8962087a34c95c5 and modified.
* @author Kevin Lee
* @since 2022-03-23
*/
trait RefinedBase[A] {
import compiletime.*

opaque type Type = A

given newRefinedCanEqual: CanEqual[Type, Type] = CanEqual.derived

def unapply(typ: Type): Option[A] = Some(typ)

@SuppressWarnings(Array("org.wartremover.warts.ToString"))
def from(a: A): Either[String, Type] =
if predicate(a) then Right(a) else Left("Invalid value: [" + a.toString + "]. " + invalidReason(a))

@SuppressWarnings(Array("org.wartremover.warts.Throw"))
def unsafeFrom(a: A): Type =
from(a).fold(err => throw new IllegalArgumentException(err), identity) // scalafix:ok DisableSyntax.throw

inline def expectedMessage(expected: String): String =
"It must be " + expected

def invalidReason(a: A): String

def predicate(a: A): Boolean

extension (typ: Type) {
inline def value: A = typ
}
}

0 comments on commit 7ce3268

Please sign in to comment.