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 # boolThe 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 intCompare 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
BeginnerCreate these variables with :=, so their types are inferred from the values:
quantitywith the value10pricewith the value99.99messagewith the value"Coddy is awesome!"is_availablewith the valuetrue
Do not change the print() lines. The program prints:
Quantity: 10
Price: 99.99
Message: Coddy is awesome!
Is available: trueTry 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler