Variable static typing question

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sprite-1

What’s the difference between

var data :Dictionary= JSON.parse(text).result

and

var data := JSON.parse(text).result as Dictionary

Or are they essentially the same? Any performance difference? Etc

:bust_in_silhouette: Reply From: Zylann

First one specifies that data must be a Dictionary regardless of the assignment.

Second one infers the type of data from the expression on the right of =, if it can be determined. That also means as is not always necessary, I think.

The reason why I added as is because Godot was complaining that it can’t infer the type from JSON.parse() but yeah I’m mostly concerned about data:Dictionary = ___ and data := ____ as Dictionary, at the end of the day,they both essentially have the same end result right?

sprite-1 | 2019-10-09 20:37

Kind of, they both tell the editor that this variable should contain a Dictionary. But it doesn’t prevent it from getting something else.

Note that the type of JSON.parse(text).result is not known in advance, that’s why you’d need to write the type. Because JSON data can either be a dictionary or an array.

Zylann | 2019-10-09 20:51