Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify type inference of class variables #762

Open
wants to merge 1 commit into
base: release/1.12
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion docs/syntax_and_semantics/class_variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
Loading