In programming, duck typing is a type system used in dynamic programming languages. The type or class of an object is less important than the method it defines.
With duck typing, you check if a class has a given method or attribute.
It comes from the saying:
If it walks like a duck and quack likes a duck, then it must be a duck
Basically in the context of the program, as long as a class has the exact name of the function; we neither care what the function specifically does nor do we care what class the specific function comes from.
Is
KeywordFor duck typing and checking for null values, we will need to use the is
keyword.
The is
keyword is used to check the data type of a given object and returns a boolean value:
5 is int # true
Frog is Animal # Does the Frog Class inherit from the Animal Class and is not empty?
# Animal Class
extends Node
class_name Animal
func fly():
print('Animal flies')
# Duck Class
extends Animal
class_name Duck
func fly():
print('this duck flies')
# Circle Class
extends Node
class_name Circle
func fly():
print('Circles are flying???')
# Node Class
extends Node2D
var animal = Animal.new()
var duck = Duck.new()
var circle = Circle.new()
# No Type Safety
"""
In this case we can pass it in everything and the function call will work
as long as the class object has that specific function name
letItFly(animal)
letItFly(duck)
letItFly(circle)
"""
func letItFly(flyingObject):
flyingObject.fly()
# With Type Safety
"""
But what if we want type safety?
Say we only want Classes and Sub-Classes of the 'Animal' class???
"""
func animalFlies(animalObject: Animal):
animalObject.fly() # comes with auto complete
"""
The problem is that an error will be thrown if the class is a null value
For Example:
var nullObject: Animal # Null Instantiation w/ type safety
In this case nullObject will make it through the animalFlies() method without warning.
The game will crash when a null object tries to call the 'fly()' because it does not exist
on a null object
In this case we have to check that null values are not sneaking through
"""
# Check for the objects casted as Nulls
# var nullObject: Animal # casted as null but will make it through this function regardless
func animalFliesSafely(animalObject: Animal):
# Option 1
if animalObject == null:
print('object/value does not fly')
return
# Option 2
if (animalObject is Animal) == false:
print('Animal Class not part of Inheritance Chain')
return
# Do whatever you want; you're an animal!
print('continue on ;)')
animalObject.fly() # without a null check, throws an error if null
Duck Typing | Godot GDScript Tutorial | Ep 19 video & article by Godot Tutorials is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License .