@@ -10,7 +10,8 @@ The L<Associative> role underlies hashes and maps, as well as other classes such
10
10
as L < MixHash > . It defines the two types that will be used in associative
11
11
classes; by default, you can use anything (literally, since any class that
12
12
subclasses L < Any > can be used) L < as a key|#Non-string_keys_(object_hash),
13
- although it will be coerced to a string, and any object as value. You can access these types using the C < of > and C < keyof > methods.
13
+ although it will be coerced to a string, and any object as value. You can
14
+ access these types using the C < of > and C < keyof > methods.
14
15
15
16
By default, any object declared with the C < % > sigil will get the Associative
16
17
role, and will by default behave like a hash, but this role will only provide
@@ -329,20 +330,54 @@ concern itself much.
329
330
= head2 Constraint value types
330
331
331
332
Place a type object in-between the declarator and the name to constraint the type
332
- of all values of a C < Hash > . Use a L < subset|/language/typesystem#subset > for
333
- constraints with a where-clause.
333
+ of all values of a C < Hash > .
334
334
335
- subset Powerful of Int where * > 9000 ;
336
- my Powerful %h{Str} ;
337
- put %h<Goku> = 9001;
335
+ my Int %h ;
336
+ put %h<Goku> = 900 ;
337
+
338
338
try {
339
- %h<Vegeta> = 900 ;
339
+ %h<Vegeta> = "string" ;
340
340
CATCH { when X::TypeCheck::Binding { .message.put } }
341
341
}
342
342
343
343
# OUTPUT:
344
344
# 9001
345
- # Type check failed in binding assignval; expected Powerful but got Int (900)
345
+ # Type check failed in assignment to %h; expected Int but got Str ("string")
346
+
347
+ You can do the same by a more readable syntax.
348
+
349
+ my %h of Int; # the same as my Int %h
350
+
351
+ If you want to constraint the type of all keys of a C < Hash > , add C < {Type} > following
352
+ the name of variable.
353
+
354
+ my %h{Int};
355
+
356
+ Even put these two constriant together.
357
+
358
+ my %h{Int} of Int;
359
+ put %h{21} = 42;
360
+
361
+ try {
362
+ %h{0} = "String";
363
+ CATCH { when X::TypeCheck::Binding { .message.put } }
364
+ }
365
+
366
+ try {
367
+ %h<string> = 42;
368
+ CATCH { when X::TypeCheck::Binding { .message.put } }
369
+ }
370
+
371
+ try {
372
+ %h<string> = "String";
373
+ CATCH { when X::TypeCheck::Binding { .message.put } }
374
+ }
375
+
376
+ # OUTPUT:
377
+ # 42
378
+ # Type check failed in binding to parameter 'assignval'; expected Int but got Str ("String")
379
+ # Type check failed in binding to parameter 'key'; expected Int but got Str ("string")
380
+ # Type check failed in binding to parameter 'key'; expected Int but got Str ("string")
346
381
347
382
= head1 Looping over hash keys and values
348
383
0 commit comments