# Improve opaque types

**URL:** <https://contributors.scala-lang.org/t/improve-opaque-types/4786>\
**Category:** Language Design\
**Created:** [January 5, 2021, 12:59pm UTC](https://contributors.scala-lang.org/t/improve-opaque-types/4786 "2021-01-05T12:59:16Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![mbloms](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/mbloms/32/1876_2.png) [@mbloms](https://contributors.scala-lang.org/u/mbloms)\
**Post date:** [January 5, 2021, 2:03pm UTC](https://contributors.scala-lang.org/t/improve-opaque-types/4786/5 "2021-01-05T14:03:18Z")

</div>

> [@gvolpe](#):
>
> Here’s the amount of code I need to write to get more or less something equivalent in Scala 3.
> 
> ```auto
> object data:
> opaque type Foo = String
> object Foo:
> def apply(v: String): Foo = v
> end Foo
> 
> extension (x: Foo) {
> def value: String = x
> }
> end data
> 
> ```

This can be written a bit more concisely:

```auto
object data:
  opaque type Foo = String
  def Foo(v: String): Foo = v
  extension (x: Foo) def value: String = x
end data

```

As many people have expressed in the other thread, the cost of writing one extra line for a wrapper function, and one extra line for a unwrapping function is lower than the cost of having to suppress these functions when they are not wanted.

Opaque types is an advanced feature, and while forcing users to write wrappers and unwrappers may be perceived as boilerplate, it’s actually more user friendly since it forces users to understand what’s going on, and is generally a better fit with the current semantics.

> [@gvolpe](#):
>
> However, it would be much better if we could use typeclass derivation for opaque types. Assuming there are instances of `Eq[String]` and `Show[String]` in scope, would something like this be possible?
> 
> ```auto
> opaque type Foo = String derives (Eq, Show)
> 
> ```

This would absolutely be possible! I actually proposed it here:

> [@Synthesize constructor for opaque types](https://contributors.scala-lang.org/t/synthesize-constructor-for-opaque-types/4616/84):
>
> Maybe this sugar wouldn’t be such a bad fit:
> 
> ```auto
> opaque type Name = String derives Show, Codec, Monoid
> 
> ```
> 
> This would essentially be equivalent to Haskell’s `GeneralisedNewtypeDeriving` .

As I already noted in that post however, this would just be convenient sugar. You can already derive instances like this:

```scala
object data:
  opaque type Foo = String
  def Foo(v: String): Foo = v
  extension (x: Foo) def value: String = x

  given (using ev: Eq[String]): Eq[Foo] = ev
  given (using ev: Show[String]): Show[Foo] = ev

```

---

_[View the full topic](https://contributors.scala-lang.org/t/improve-opaque-types/4786)._
