|
| 1 | +/* |
| 2 | + * Scala (https://www.scala-lang.org) |
| 3 | + * |
| 4 | + * Copyright EPFL and Lightbend, Inc. |
| 5 | + * |
| 6 | + * Licensed under Apache License 2.0 |
| 7 | + * (http://www.apache.org/licenses/LICENSE-2.0). |
| 8 | + * |
| 9 | + * See the NOTICE file distributed with this work for |
| 10 | + * additional information regarding copyright ownership. |
| 11 | + */ |
| 12 | + |
| 13 | +package scala |
| 14 | + |
| 15 | +/** |
| 16 | + * `ValueOf[T]` provides the unique value of the type `T` where `T` is a type which has a |
| 17 | + * single inhabitant. Eligible types are singleton types of the form `stablePath.type`, |
| 18 | + * Unit and singleton types corresponding to value literals. |
| 19 | + * |
| 20 | + * Instances of `ValueOf[T]` are provided implicitly for all eligible types. Typically |
| 21 | + * an instance would be required where a runtime value corresponding to a type level |
| 22 | + * computation is needed. |
| 23 | +
|
| 24 | + * For example, we might define a type `Residue[M <: Int]` corresponding to the group of |
| 25 | + * integers modulo `M`. We could then mandate that residues can be summed only when they |
| 26 | + * are parameterized by the same modulus, |
| 27 | + * |
| 28 | + * {{{ |
| 29 | + * case class Residue[M <: Int](n: Int) extends AnyVal { |
| 30 | + * def +(rhs: Residue[M])(implicit m: ValueOf[M]): Residue[M] = |
| 31 | + * Residue((this.n + rhs.n) % valueOf[M]) |
| 32 | + * } |
| 33 | + * |
| 34 | + * val fiveModTen = Residue[10](5) |
| 35 | + * val nineModTen = Residue[10](9) |
| 36 | + * |
| 37 | + * fiveModTen + nineModTen // OK == Residue[10](4) |
| 38 | + * |
| 39 | + * val fourModEleven = Residue[11](4) |
| 40 | + * |
| 41 | + * fiveModTen + fourModEleven // compiler error: type mismatch; |
| 42 | + * // found : Residue[11] |
| 43 | + * // required: Residue[10] |
| 44 | + * }}} |
| 45 | + * |
| 46 | + * Notice that here the modulus is encoded in the type of the values and so does not |
| 47 | + * incur any additional per-value storage cost. When a runtime value of the modulus |
| 48 | + * is required in the implementation of `+` it is provided at the call site via the |
| 49 | + * implicit argument `m` of type `ValueOf[M]`. |
| 50 | + */ |
| 51 | +@scala.annotation.implicitNotFound(msg = "No singleton value available for ${T}.") |
| 52 | +final class ValueOf[T](val value: T) extends AnyVal |
0 commit comments