Class operators
There are a couple operators for working with classes.
Type cast with "as"​
The as operator is used with objects that are instances of a class. For example, a as b can be used to test whether a is an instance of the base class b.
In order to use this operator, the class must extend from the special class_id_base base class.
Suppose we define classes cat and dog that both extend from an animal base class:
class animal extends class_id_base
var name: string
end class
class cat extends animal
func meow()
console::print("meow")
end func
end class
class dog extends animal
func bark()
console::print("bark")
end func
end class
Objects created with new cat() or new dog() can be assigned to a variable of type animal. But the animal type cannot "see" specialized members such as meow() or bark(). In order to access those members, we must "cast" to the type.
module main
func talk(a: animal)
var c: cat, d: dog
# See if we can cast "a" as a cat
a as cat -> c
# If "a" is not a cat, then "c" will be null
if c <> null then
c.meow()
else
# See if we can cast "a" as a dog
a as dog -> d
# If "a" is not a dog, then "d" will be null
if d <> null then
d.bark()
end if
end if
end func
func start()
console::init()
main::talk(new cat())
main::talk(new dog())
end func
end module
Note: To cast types that are not classes, use the conversion operators such as
to_byte()instead ofas.
class_id() operator​
This operator returns a pair value that uniquely identifies a Hybrix class, useful for detecting the type of an object. The class must extend from the special class_id_base base class. The compiler assigns numbers such that a class and all of its subclasses are assigned values in a contiguous range; this allows the as operator to be implemented as an inexpensive range test. However, the specific starting number or traversal order is not guaranteed. It may change in future compiler releases. Programs should not rely on specific class_id values or their ordering.
Example:
class animal extends class_id_base
end class
class cat extends animal
end class
class dog extends animal
end class
module main
func start()
var id: pair
# The example values shown below are not guaranteed
class_id(animal) -> id # 1002
class_id(cat) -> id # 1003
class_id(dog) -> id # 1004
end func
end module