Skip to content

Commit c4ed1c3

Browse files
committed
Explain and test that applyDynamic and selectDynamic can have using clauses
1 parent 4ab3a1e commit c4ed1c3

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

docs/docs/reference/changed-features/structural-types-spec.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def applyDynamic(name: String, ctags: ClassTag[?]*)(args: Any*): T
4343
```
4444
Both versions are passed the actual arguments in the `args` parameter. The second version takes in addition a vararg argument of class tags that identify the method's parameter classes. Such an argument is needed
4545
if `applyDynamic` is implemented using Java reflection, but it could be
46-
useful in other cases as well.
46+
useful in other cases as well. `selectDynamic` and `applyDynamic` can also take additional context parameters in using clauses. These are resolved in the normal way at the callsite.
4747

4848
Given a value `v` of type `C { Rs }`, where `C` is a class reference
4949
and `Rs` are structural refinement declarations, and given `v.a` of type `U`, we consider three distinct cases:

tests/run/structural-contextual.scala

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
trait Resolver:
2+
def resolve(label: String): Any
3+
4+
class ResolvingSelectable extends Selectable:
5+
def selectDynamic(label: String)(using r: Resolver): Any =
6+
r.resolve(label)
7+
def applyDynamic(label: String)(args: Any*)(using r: Resolver): Any =
8+
r.resolve(label).asInstanceOf[Any => Any].apply(args.head)
9+
10+
type Person = ResolvingSelectable {
11+
val name: String
12+
val age: Int
13+
def likes(other: String): Boolean
14+
}
15+
16+
17+
@main def Test =
18+
given Resolver:
19+
def resolve(label: String) = label match
20+
case "name" => "Emma"
21+
case "age" => 8
22+
case "likes" => (food: String) => food == "Cake"
23+
24+
val emma = ResolvingSelectable().asInstanceOf[Person]
25+
26+
assert(emma.name == "Emma")
27+
assert(emma.age == 8)
28+
assert(emma.likes("Cake"))

0 commit comments

Comments
 (0)