-
Notifications
You must be signed in to change notification settings - Fork 0
Type Inference
If the type of a variable, expression, or function call is not known at compile time, the engine will try to guess the type based on context. For example:
int a = 1; // Type is known (int)
int b = 2; // Type is known (int)
object ob = a; // Type is unknown at compile time, the variable ob could point to an object of any type
return b + ob; // Returns 3, ccl assumes that ob points to an int type because b is an int type
If you perform a binary operation and one of the values' types is unknown, ccl infers that they are both the same type. The variable of unknown type, assumes the type of the other variable if it is known.
If neither type is known at compile time, the engine cannot make a guess as to which type they are and this trick will not work.
int a = 1; // Type is known (int)
int b = 2; // Type is known (int)
object ob = a; // Type is unknown at compile time, the variable ob could point to an object of any type
return ob + ob; // Fails, because there is no + operation defined for Object and Object
// The engine, does not know at compile-time that these will be ints at run-time
return (int)ob + ob; // This works, because at least one variable will have a defined int type
// And the engine can infer that the other one must also be an int
There are times when this will fail! One example is if you are performing an operation on different types
string str = "Hello "; // Type is known (int)
int b = 2; // Type is known (int)
object ob = b; // Type is unknown at compile time, the variable ob could point to an object of any type
return str + ob; // This will fail, because it is going to assume that ob will be a string
// We set ob as an int
This will fail, even though string + int
is valid, because the engine is going to pass in an int as if it is a string and it will crash.
Questions? Comments?
Contact me at kameron@creation-wasteland.com
Follow on Twitter: @wasteland_11
Copyright 2019 © Kameron Brooks