Menu
CoddyTech

Type Inference

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 11 of 92.

When the value already shows the type, writing the type again is repetitive. With :=, GDScript infers the type from the value:

var hp := 10 # int
var speed := 2.5 # float
var player_name := "Ada" # String
var is_alive := true # bool

The type is fixed when the variable is created. var hp := 10 means the same as var hp: int = 10, so a value of another type is an error:

var hp := 10
hp = 25 # OK: a new int
hp = "ten" # Error: hp is an int

Compare it with plain =: after var hp = 10, the variable has no fixed type, and hp = "ten" is allowed.

The type comes from the value, so := needs a value that has a type. var target := null is an error, because null does not say which type the variable should have. Write the type yourself in that case.

challenge icon

Challenge

Beginner

Create these variables with :=, so their types are inferred from the values:

  • quantity with the value 10
  • price with the value 99.99
  • message with the value "Coddy is awesome!"
  • is_available with the value true

Do not change the print() lines. The program prints:

Quantity: 10
Price: 99.99
Message: Coddy is awesome!
Is available: true

Try it yourself

extends Node

func _ready():
	# Create the variables below
	
	# Don't change the lines below
	print("Quantity: ", quantity)
	print("Price: ", price)
	print("Message: ", message)
	print("Is available: ", is_available)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler