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

quasi-Opaque types in Scala 2 #593

Open
halotukozak opened this issue Jun 28, 2024 · 0 comments · May be fixed by #592
Open

quasi-Opaque types in Scala 2 #593

halotukozak opened this issue Jun 28, 2024 · 0 comments · May be fixed by #592

Comments

@halotukozak
Copy link
Member

halotukozak commented Jun 28, 2024

In default Scala 2, we have a way to alias types. This is great as a way to make code more readable, but if your type logically has a more limited range of support then the type won't enforce this. Or if the type you are working with is used in different places to mean different things, then implicits wont know what to pick.

Opaque type aliases from Scala 3 provide type abstraction without any overhead. In Scala 2, a similar result could be achieved with value classes, but it has limitations and enforces "boxed" syntax, e.g.:

final case class ID(value: String) extends AnyVal

Seq[ID](...).forEach{ id=>
  println("Sth sth" + id.value)
}

Seq[String](ID("asdsadas").value)

My proposition allows to define quasi-opaque type without runtime overhead and with full IDE support.

object ID extends Opaque.Default[String]

  Seq[String](ID("DASDAS"))
  /*
  type mismatch;
    found   : CastableTest.this.ID.Type
    (which expands to)  com.avsystem.commons.opaque.Opaque.Hidden[String,CastableTest.this.ID.Tag]
    required: String
   */
  Seq[ID.Type]("DASDAS")
  /*
  type mismatch;
     found   : String("DASDAS")
     required: CastableTest.this.ID.Type
        (which expands to)  com.avsystem.commons.opaque.Opaque.Hidden[String,CastableTest.this.ID.Tag]
  Seq[ID.Type]("DASDAS")
   */

Seq[ID](...).forEach{ id=>
  println("Sth sth" + id)
}

object ID2 extends Subopaque.Default[String]

Seq[String](ID2("DASDAS")) //ok

Opaque is equivalent to

opaque type T = Original

SubOpaque is equivalent to:

opaque type T <: Original = Original

in Scala 3

@halotukozak halotukozak linked a pull request Jun 28, 2024 that will close this issue
@halotukozak halotukozak linked a pull request Jun 28, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant