Interfaces in GDScript

In GDScript, interfaces are not explicitly defined. Instead, we use duck typing, which means that any object can be used as long as it has the required methods. Here’s how we can implement the concept of interfaces in GDScript:

extends Node

# We don't define an interface, but we'll use these method names
# area() and perim() as our "interface"

class Rect:
    var width: float
    var height: float
    
    func _init(w: float, h: float):
        width = w
        height = h
    
    func area() -> float:
        return width * height
    
    func perim() -> float:
        return 2 * width + 2 * height

class Circle:
    var radius: float
    
    func _init(r: float):
        radius = r
    
    func area() -> float:
        return PI * radius * radius
    
    func perim() -> float:
        return 2 * PI * radius

# This function can work with any object that has area() and perim() methods
func measure(shape):
    print(shape)
    print(shape.area())
    print(shape.perim())

func _ready():
    var r = Rect.new(3, 4)
    var c = Circle.new(5)
    
    # We can use both Rect and Circle with the measure function
    measure(r)
    measure(c)

In this GDScript example, we’ve implemented the concept of interfaces using duck typing. Here’s a breakdown of the code:

  1. We define two classes, Rect and Circle, each with area() and perim() methods. These methods serve as our implicit “interface”.

  2. The measure() function takes any object as an argument. It doesn’t specify a type, allowing it to work with any object that has area() and perim() methods.

  3. In the _ready() function (which is called when the script is loaded), we create instances of Rect and Circle and pass them to the measure() function.

  4. GDScript’s duck typing allows us to use both Rect and Circle objects with the measure() function, as long as they have the required methods.

To run this script in Godot:

  1. Create a new script and paste this code into it.
  2. Attach the script to a Node in your scene.
  3. Run the scene.

The output will be similar to:

[Rect:1]
12.0
14.0
[Circle:2]
78.539816
31.415926

This example demonstrates how GDScript can achieve interface-like behavior through duck typing, allowing for flexible and reusable code without explicit interface declarations.