Skip to content

Commit

Permalink
Fix: SubtypeCustom[A] should behave like subtype of A (#1328)
Browse files Browse the repository at this point in the history
* Add test validating that passing a `Subtype[String]` and a `SubtypeCustom[String]` to a function asking for a `String` does compile

* clean

* Fix: `SubtypeCustom[A]` should behave like subtype of `A`

* Add missing `override`
  • Loading branch information
guizmaii authored May 31, 2024
1 parent 3926eca commit 83c8fc3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,10 @@ object NewtypeSpecTypes {
Pin(1000, 1001, 9998, 9999)

object Palindrome extends NewtypeCustom[String] {
protected def validate(value: String) =
override protected def validate(value: String) =
PalindromeValidator.validate(value)

protected inline def validateInline(inline value: String) =
override protected inline def validateInline(inline value: String) =
${ PalindromeValidator.validateInlineImpl('value) }
}

Expand All @@ -106,6 +106,15 @@ object NewtypeSpecTypes {
def unsafeWrap(s: String): Type = wrap(s)
}

type NonEmptyString = NonEmptyString.Type
object NonEmptyString extends SubtypeCustom[String] {
override protected def validate(value: String) =
NonEmptyStringValidator.validate(value)

override protected inline def validateInline(inline value: String) =
${ NonEmptyStringValidator.validateInlineImpl('value) }
}

// These should compile
GithubHeaderKey("X-Github-Request-Id")
GithubHeaderKey("X-GitHub-Request-Id")
Expand All @@ -125,4 +134,9 @@ object NewtypeSpecTypes {
GmailEmail("[email protected]")
GmailEmail("[email protected]")
GmailEmail("[email protected]")

def takeString(s: String): Unit = ()
// These should compile
takeString(GithubHeaderKey("X-Github-Request-Id"))
takeString(NonEmptyString("Hello"))
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,9 @@ object PalindromeValidator
extends Validator[String](str =>
if (str.reverse == str) Right(()) else Left(AssertionError.Failure("isPalindrome"))
)

object NonEmptyStringValidator
extends Validator[String]((s: String) =>
if (s.isBlank) Left(AssertionError.failure("NonEmptyString cannot be empty"))
else Right(())
)
2 changes: 1 addition & 1 deletion core/shared/src/main/scala-3/zio/prelude/Newtype.scala
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ abstract class NewtypeCustom[A] {
}

abstract class SubtypeCustom[A] extends NewtypeCustom[A] {
type Base <: A
override type Type <: A
}

abstract class Newtype[A] extends NewtypeCustom[A] {
Expand Down

0 comments on commit 83c8fc3

Please sign in to comment.