what's the difference between static, final and const members at compile time in Dart? [closed]
Asked Answered
P

2

5

Like the title suggests, what's the difference between static, final and const at compile time in Dart?

When are they computed and when are memory allocated for each type? Can a heavy use of static variables lead to performance issues or OOM?

Prentiss answered 27/12, 2018 at 14:56 Comment(4)
Possible duplicate of what is the difference in between ''const'' and ''final'' keyword in Dart?Fibroid
It's related, but I'm actually more confused with static/const differences. I edited the question to make this more clear.Jadeite
You should probably perform some basic research before going any further. static const dart site:stackoverflow.com.Fibroid
You'r right. My bad. I would delete the question but I feel like it would be unfair to the excellent answers below.Jadeite
F
13

static is to declar class level members (methods, fields, getters/setters). They are in the class' namespace. They can only be accessed from within the class (not subclasses) or with the class name as prefix.

class Foo {
  static bar() => print('bar');

  void baz() => bar(); // ok
}

class Qux extens Foo {
  void quux() => bar(); // error. There is no `bar()` on the `Qux` instance
}

main() {
  var foo = Foo();
  foo.bar(); // error. There is no `bar` on the `Foo` instance.
  Foo.bar(); // ok
}

const is for compile time constants. Dart allows a limited set of expressions to calculate compile time constants. const instances are canonicalized. This means multiple const Text('foo') (with the same 'foo' parameter value) are canonicalized and only one single instance will be created no matter where and how often this code occurs in your app.

class Foo {
  const Foo(this.value);

  // if there is a const constructor then all fields need to be `final`
  final String value;
}
void main() {
  const bar1 = Foo('bar');
  const bar2 = Foo('bar');
  identical(bar1, bar2); // true 
}

final just means it can only be assigned to at declaration time.

For instance fields this means in in field initializers, by constructor parameters that assign with this.foo, or in the constructor initializer list, but not anymore when the constructor body is executed.

void main() {
  final foo = Foo('foo');
  foo = Foo('bar'); // error: Final variables can only be initialized when they are introduced
}

class Foo {
  final String bar = 'bar';
  final String baz;
  final String qux;

  Foo(this.baz);
  Foo.other(this.baz) : qux = 'qux' * 3;
  Foo.invalid(String baz) {
  // error: Final `baz` and `qux` are not initialized
    this.baz = baz;         
    this.qux = 'qux' * 3;
  }
}
Forsooth answered 27/12, 2018 at 15:2 Comment(5)
Aha, I think i get it. Does this mean that both const and static members have allocated memory at build time where as instance members are allocated for at instance creation?Jadeite
As far as I remember static members are lazily initialized on first access, which means they are allocated at runtime, but you can have static const ;-) static is like a top-level field (outside any function or class) just with the class name as additional namespace.Explore
This is a great explanation, thank you!Hardee
@GünterZöchbauer I am confused. in Java static final can mean compile time. And in Kotlin, const is like static final of Java. And here in Dart, static and const. Does static also is created on compile time?Coppice
@Coppice static is unrelated to compile time. It just means it's related to the type, but not to object of this type. This way Foo acts merely as a namespace for static members.Explore
B
4

A static variable does not require an instance of the class to use.

Example:

class Math {
  static var double staticPi = 3.14;
  double var pi = 3.14;
}

class ClassThatUsesMath {
  print(Math.staticPi);

  // Non-static variable must initialize class first:
  Math math = Math();
  print(math.pi);
}

A final variable's value cannot be changed after it is assigned a value.

Example:

class Math {
  final var pi = 3.14;
  pi = 3.1415;  // Error!
}

A const variable is similar to a final one in that it is immutable (cannot be changed). However, const values must be able to be calculated at compile time. const values will also be reused instead of being recalculated.

Example:

class MathClass {
  const var section = 4;
  const var examTime = DateTime.now();  // Error! Cannot be determined at compile time.
}
Brinton answered 27/12, 2018 at 15:10 Comment(2)
In the first example, could I change staticPis value to 2.72 and that value would persist until the program terminates? If i create 2 Math objects, can I change staticPi on one of them or are static variables not a member of the instance?Jadeite
Yes; static variables belong to the class, not the instance so changing the variable from anywhere will change it wherever else it is being used for the lifetime of the application.Brinton

© 2022 - 2024 — McMap. All rights reserved.