Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

New optional array access operator may fail on compilation with nil arrays #593

Discussion options

If the compiler knows a variable is nil, the (very cool!) ?.[] operator fails.
Examples:
The following expression fails on compilation:

let arr = nil;
arr?.[3]

The error is:
type <nil>[int] is undefined (4:6)

This one, however, succeed:

let x = 3;
let arr = x < 4 ? nil : [1];
arr?.[0]
You must be logged in to vote

Compiler don't know the resulting type of cond ? x : y expression on compilation step.

If type(x) == type(y), compiler assumes return type of whole expression cond ? x : y is type(x).
If type(x) != type(y), compiler assumes retutn type of whole expression cond ? x : y is any.

And in your example: type(nil) != type([1]), so compiler assigns arr any type. And any may support indexing arr[0].

Replies: 1 comment

Comment options

Compiler don't know the resulting type of cond ? x : y expression on compilation step.

If type(x) == type(y), compiler assumes return type of whole expression cond ? x : y is type(x).
If type(x) != type(y), compiler assumes retutn type of whole expression cond ? x : y is any.

And in your example: type(nil) != type([1]), so compiler assigns arr any type. And any may support indexing arr[0].

You must be logged in to vote
0 replies
Answer selected by antonmedv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Converted from issue

This discussion was converted from issue #591 on March 04, 2024 22:16.

AltStyle によって変換されたページ (->オリジナル) /