From 3f684f41c5766034e64ebc715923ebdf1283c533 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Tue, 28 May 2024 11:42:15 +0200 Subject: [PATCH] Clarify type inference of class variables --- docs/syntax_and_semantics/class_variables.md | 23 +++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/docs/syntax_and_semantics/class_variables.md b/docs/syntax_and_semantics/class_variables.md index 4b45316c2..9ea309578 100644 --- a/docs/syntax_and_semantics/class_variables.md +++ b/docs/syntax_and_semantics/class_variables.md @@ -24,7 +24,28 @@ Counter.instances # => 3 Class variables can be read and written from class methods or instance methods. -Their type is inferred using the [global type inference algorithm](type_inference.md). +When initialized with a default value, the [type inference algorithm](type_inference.md) can often implicitly determine the type of the variable. + +```cr +module InferredTypes + @@integer = 1 # : Int32 + @@string = "" # : String +end +``` + +It won't be able to infer the type of complex expressions involving methods calls, for example. +In these cases, the variable needs to be typed explicitly. + +```cr +def generate_foo + 1 +end + +module NonInferrableType + @@untyped = generate_foo() # Error: can't infer the type of class variable '@@foo' of NonInferrableTypes + @@typed : Int32 = generate_foo() +end +``` Class variables are inherited by subclasses with this meaning: their type is the same, but each class has a different runtime value. For example: