Skip to content

Commit 9331dd9

Browse files
committed
Add section on computable field names to reference doc page
1 parent 5a31ba1 commit 9331dd9

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

docs/_docs/reference/experimental/named-tuples.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,44 @@ then
195195
c f (age = 1)
196196
```
197197
will now construct a tuple as second operand instead of passing a named parameter.
198+
199+
### Computed Field Names
200+
201+
The `Selectable` trait now has a `Fields` type member that can be instantiated
202+
to a named tuple.
203+
204+
```scala
205+
trait Selectable:
206+
type Fields <: NamedTuple.AnyNamedTuple
207+
```
208+
209+
If `Fields` is instantiated in a subclass of `Selectable` to some named tuple type,
210+
then the available fields and their types will be defined by that type. Assume `n: T`
211+
is an element of the `Fields` type in some class `C` that implements `Selectable`,
212+
that `c: C`, and that `n` is not otherwise legal as a name of a selection on `c`.
213+
Then `c.n` is a legal selection, which expands to `c.selectDynamic("n").asInstanceOf[T]`.
214+
215+
It is the task of the implementation of `selectDynamic` in `C` to ensure that its
216+
computed result conforms to the predicted type `T`
217+
218+
As an example, assume we have a query type `Q[T]` defined as follows:
219+
220+
```scala
221+
trait Q[T] extends Selectable:
222+
type Fields = NamedTuple.Map[NamedTuple.From[T], Q]
223+
def selectDynamic(fieldName: String) = ...
224+
```
225+
226+
Assume in the user domain:
227+
```scala
228+
case class City(zipCode: Int, name: String, population: Int)
229+
val city: Q[City]
230+
```
231+
Then
232+
```scala
233+
city.zipCode
234+
```
235+
has type `Q[Int]` and it expands to
236+
```scala
237+
city.selectDynamic("zipCode").asInstanceOf[Q[Int]]
238+
```

0 commit comments

Comments
 (0)