Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make RefinedBase extend NewtypeBase to support unwrapping (getting value) for Refined and InlinedRefined types with Coercible #46

Closed
kevin-lee opened this issue Dec 3, 2023 · 0 comments · Fixed by #48
Assignees
Labels
Milestone

Comments

@kevin-lee
Copy link
Owner

Summary

Make RefinedBase extend NewtypeBase to support unwrapping (getting value) for Refined and InlinedRefined types with Coercible

Version

unreleased

Description

type MyType = MyType.Type
object MyType extends InlinedRefined[String] {

  override inline def invalidReason(a: String): String =
    "It has to be a non-empty String but got [" + a + "]"

  override inline def predicate(a: String): Boolean = a != ""

  override inline def inlinedPredicate(inline a: String): Boolean = a != ""
}
type Something = Something.Type
object Something extends InlinedRefined[Int] {

  private def inlinedPredicate0(a: Expr[Int])(using Quotes): Expr[Boolean] = {
    import quotes.reflect.*
    a.asTerm match {
      case Inlined(_, _, Literal(IntConstant(num))) =>
        try {
          validate(num)
          Expr(true)
        } catch {
          case _: Throwable => Expr(false)
        }
      case _ =>
        report.error(
          "Something must be a Int literal.",
          a,
        )
        Expr(false)
    }

  }

  override inline def inlinedPredicate(inline a: Int): Boolean = ${ inlinedPredicate0('a) }

  override def invalidReason(a: Int): String = s"The number is a negative Int. [a: ${a.toString}"

  override def predicate(a: Int): Boolean =
    try {
      validate(a)
      true
    } catch {
      case _: Throwable => false
    }
}
def unwrap[A, B](a: A)(using coercible: Coercible[A, B]): B = coercible(a)

unwrap(MyType("abc"))
// String = abc

unwrap(Something(999))
// Int = 999
@kevin-lee kevin-lee added the task label Dec 3, 2023
@kevin-lee kevin-lee added this to the m1 milestone Dec 3, 2023
@kevin-lee kevin-lee self-assigned this Dec 3, 2023
kevin-lee added a commit that referenced this issue Dec 4, 2023
… (getting value) for Refined and InlinedRefined types with Coercible
kevin-lee added a commit that referenced this issue Dec 4, 2023
… (getting value) for Refined and InlinedRefined types with Coercible
kevin-lee added a commit that referenced this issue Dec 4, 2023
… (getting value) for Refined and InlinedRefined types with Coercible
kevin-lee added a commit that referenced this issue Dec 4, 2023
… (getting value) for Refined and InlinedRefined types with Coercible
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
1 participant