Godot Version
4.4.1.Stable
Question
Static typing in Godot is very useful. I’ve seen some behaviour that works when auto typing is involved, but don’t know how to replicate by forcing a type.
When auto typing a variable as a reference to a Class, it shows the static functions.
Adding GDScript as type seems to keep it working, which gives me the impression that this may be the type the variable receives.
But when passing this variable as a parameter, it does not give the autocompletion. (obviously because the type is GDScript and nothing linking to BareScreen)
Is it possible to static type this variable and gain the code completions?
I could be wrong but I think this is because in the first two cases, base_screen
is actually the type BareScreen
BUT in the 3rd case, you pass the variable as GDScript
, and not as BareScreen
.
Try to replace (bare_screen: GDScript)
with (bare_screen: BareScreen)
I get what you mean, but then the variable will expect an instantiated version of the class and i want to reference a reference to the class type itself
I’d be interested in why you want to do this? Given you can just call BareScreen.static_function()
directly.
The only reason I could think of was for mocking purposes in tests
I’ve not tried writing any unit tests for GDScript but I’ve got a lot of experience writing Java unit tests. Personally, I always considered mocking static functions a design smell, and only ever needed to do it for third party libraries that [to me] didn’t seem like they were designed with testing in mind.
If this is the reason you could pass a Callable around. However, that doesn’t help with type safety as as far as I can tell there isn’t any way of typing Callable.
Then Script
(or GDScript
) is how you can store a “type” in a variable. Maybe it would help to describe what led on this solution? What is your big picture problem?
2 Likes
I have an Array with class references which all extend from BareScreen:
[A_BareScreen, B_BareScreen…]
In all these classes i overwrite the static function to use the constant values of this class.
(I know overwriting a static function creates a copy and doesn’t really overwrite the function.)
I want to loop through the array and call the static function on each one without hardcoding each call to the static function as this array is meant to grow and be flexible.
Even though it works completely fine without using static typing. It just makes me really curious how using the static typing combination := gives you the static functions available, and how to create this auto static typing manually to better understand it.
Bonus curiousity question:
Why can’t i create a const variable with a reference to a class as in