Menu
CoddyTech

Type Declaration

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

A variable created with plain var can hold any type of value, and the type can change later:

var score = 10
score = "ten" # allowed: score now holds a String

You can also declare the type of a variable. Write a colon and the type after the name:

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

A typed variable can only hold values of its type. Assigning a value of another type is an error, and Godot reports it before the program runs:

hp = 25 # OK: a new int
hp = "ten" # Error: a String cannot go in an int variable

One exception: an int stored in a float variable becomes a float, so var price: float = 5 stores 5.0.

Declared types catch mistakes before the program runs, and the Godot style guide recommends them. From this lesson on, the programs in this course give every variable a type.

challenge icon

Challenge

Beginner

Declare these variables with their types, under the comment:

  • an int named count with the value 10
  • a float named total with the value 150.75
  • a String named grade with the value "A"
  • a bool named is_active with the value false
  • a String named user_name with the value "Bob123"

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

Count: 10
Total: 150.75
Grade: A
Active: false
User Name: Bob123

Try it yourself

extends Node

func _ready():
	# Declare the typed variables below
	
	# Don't change the lines below
	print("Count: ", count)
	print("Total: ", total)
	print("Grade: ", grade)
	print("Active: ", is_active)
	print("User Name: ", user_name)
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