Why I cannot return null / Nil from a method that returns a typed array?

Godot Version

4.3

Question

I have a method that returned an object, or null if the object does not exits. It works fine.

func my_method() -> MyClass:
    return some_dictionary.get("my key")

Now, I have a similar one that returns an Array[MyClass], for this one when there is no match in the dictionary I get an error:

Trying to return value of type “Nil” from a function whose return type is “Array[Object]”.

The code is pretty much the same

func my_method() -> Array[MyClass]:
    return arrays_dictionary.get("some key")

I was assuming a typed Array is just an object, so I could have a null pointer, but it seems it’s not?

The hint is in the error: return type is "Array[Object]'".

Your function returns an array of objects, not an object. You need to either wrap the result of your get() in an array, or change the return type to MyClass.

With what you have, it ought to return an empty array on failure, not a nil.

2 Likes

Yeah, I ended up returning an empty array, my confusion comes from the fact that in other languages an array of objects is also an object. I’m surprised this is not the case in GDScript. Anyway, thanks.

Fyi arrays are not class objects. Neither are dictionaries. You cannot inherit from them nor extend them. I know in pure oop they would be, e.g. Smalltalk where everything is an object.

2 Likes