Skip to content

Add support for nullable static types in GDScript #162

@aaronfranke

Description

@aaronfranke

Describe the project you are working on: This applies to many projects. This is an offshoot from #737, example use cases and other discussions are welcome.

Describe the problem or limitation you are having in your project:

Let's say you have a method that accepts a 2D position, which would look something like this:

func whatever(vec):

A problem with this is that there's no type safety, so the function could unexpectedly break if the passed-in value is not a Vector2. One option is to use static typing:

func whatever(vec: Vector2):

This works, and now it's not possible for users to, for example, pass in a Color or any other type that's invalid for this method. However, now you can't pass in null to mean N/A or similar.

Describe how this feature / enhancement will help you overcome this problem or limitation:

If GDScript's static typing system allowed specifying nullable types, we would be able to restrict the type to either a valid value or null. The presence of a valid value can then be detected simply by checking if it is not null, as non-null nullable typed values must be valid values.

Show a mock up screenshots/video or a flow diagram explaining how your proposal will work:

My suggestion is to simply allow this by adding a question mark after the type name, which is the same syntax used in C#, Kotlin, and TypeScript. User code could look something like this:

func whatever(vec: Vector2?):

Describe implementation detail for your proposal (in code), if possible:

Aside from the above, I don't have any specific ideas on how it would be implemented.

However, I will add that we could expand this idea for engine methods. Many parts of Godot accept a specific type or null to mean invalid or N/A, or return a specific type or null when there is nothing else to return. For example, Plane's intersect methods return a Vector3 if an intersection was found, or null if no intersection was found. Nullable static typing could essentially self-document such methods by showing that the return type is Vector3? instead of Vector3.

If this enhancement will not be used often, can it be worked around with a few lines of script?: The only option is to not use static typing if you need the variable to be nullable.

Is there a reason why this should be core and not an add-on in the asset library?: Yes, because it would be part of GDScript.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    On Hold

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions