diff --git a/modules/refined4s-core/shared/src/main/scala/refined4s/Refined.scala b/modules/refined4s-core/shared/src/main/scala/refined4s/Refined.scala index 929dd55..2efa7f7 100644 --- a/modules/refined4s-core/shared/src/main/scala/refined4s/Refined.scala +++ b/modules/refined4s-core/shared/src/main/scala/refined4s/Refined.scala @@ -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 - } } diff --git a/modules/refined4s-core/shared/src/main/scala/refined4s/RefinedBase.scala b/modules/refined4s-core/shared/src/main/scala/refined4s/RefinedBase.scala new file mode 100644 index 0000000..8d33bbb --- /dev/null +++ b/modules/refined4s-core/shared/src/main/scala/refined4s/RefinedBase.scala @@ -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 + } +}