@@ -315,6 +315,30 @@ not bind an Array that has the wrong type to a typed C<@>-sigiled variable:
315
315
my Int @b := Array[Int].new(1,2,3); # fine
316
316
@b := Array.new(1,2,3); # error: Type check failed in binding
317
317
318
+ When working with typed arrays, it is important to remember that they are
319
+ nominally typed. This means the declared type of an array is what matters.
320
+ Given the following sub declaration:
321
+
322
+ sub mean(Int @a) {
323
+ @a.sum / @a.elems
324
+ }
325
+
326
+ Calls that pass an Array[Int] will be successful:
327
+
328
+ my Int @b = 1,3,5;
329
+ say mean(@b); # @b is Array[Int]
330
+ say mean(Array[Int].new(1,3,5)); # Anonymous Array[Int]
331
+ say mean(my Int @ = 1,3,5); # Another anonymous Array[Int]
332
+
333
+ However, the following calls will all fail, due to passing an untyped array,
334
+ even if the array just happens to contain Int values at the point it is
335
+ passed:
336
+
337
+ my @c = 1,3,5;
338
+ say mean(@c); # Fails, passing untyped Array
339
+ say mean([1,3,5]); # Same
340
+ say mean(Array.new(1,3,5)); # Same again
341
+
318
342
Note that in any given compiler, there may be fancy, under-the-hood, ways to
319
343
bypass the type check on arrays, so when handling untrusted input, it can be
320
344
good practice to perform additional type checks, where it matters:
0 commit comments