Skip to content

Cannot assign Array[A_Extend] to Array[A] in GDScript #100798

Closed as not planned
Closed as not planned
@luckyabsoluter

Description

Tested versions

v4.3.stable.official [77dcf97]

System information

v4.3.stable.official [77dcf97]

Issue description

When attempting to assign an Array of a subclass (Array[A_Extend]) to an Array of its parent class (Array[A]), the GDScript compiler throws the following error:

Value of type "Array[A_Extend]" cannot be assigned to a variable of type "Array[A]".

This behavior contradicts the expected polymorphism in object-oriented programming where a subclass should be assignable to a parent class reference.

Expected Behavior:

The array_A_Extend (an array of subclass A_Extend) should be assignable to array_A (an array of parent class A) without any errors.

Actual Behavior:

An error is thrown, preventing the assignment:
Value of type "Array[A_Extend]" cannot be assigned to a variable of type "Array[A]".

Steps to reproduce

Assign

  1. Create a new Godot project.
  2. Add the following script to a Node:
extends Node

class A:
    pass

class A_Extend extends A:
    pass

func _ready():
    var array_A: Array[A] = []
    var array_A_Extend: Array[A_Extend] = []

    array_A = array_A_Extend  # Error: Value of type "Array[A_Extend]" cannot be assigned to a variable of type "Array[A]".
    #array_A.assign(array_A_Extend)  # bug workaround
  1. Check the script for errors.

Argument

  1. Create a new Godot project.
  2. Add the following script to a Node:
extends Node

class A:
    pass

class A_Extend extends A:
    pass

func _ready():
    var array_A: Array[A] = []
    var array_A_Extend: Array[A_Extend] = []

    need_A(array_A_Extend)  # Error: Invalid argument for "need_A()" function: argument 1 should be "Array[A]" but is "Array[A_Extend]".
    #array_A.assign(array_A_Extend)  # bug workaround
    #need_A(array_A)

func need_A(p: Array[A]):
    pass
  1. Check the script for errors.

Argument but No error

  1. Create a new Godot project.
  2. Add the following script to a Node:
extends Node

class A:
    func _to_string():
        return "A"

class A_Extend extends A:
    func _to_string():
        return "A_Extend"

func _ready():
    need_A([A_Extend.new()])

func need_A(array_A: Array[A]):
    print(array_A)
  1. No error!

Minimal reproduction project (MRP)

N/A

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions