I think I remember something like this from python, maybe it was the walrus operator? idk.
but is there a way to set an attribute while returning the value? something like this:
class Foo {
late String foo;
Foo();
String setFoo() => foo := 'foo';
}
f = Foo();
x = f.setFoo();
print(x);
// 'foo'
CodePudding user response:
I think I found it, that is, for the case that foo can be null:
class Foo {
String? foo;
Foo();
String setFoo() => foo ??= 'foo';
}
CodePudding user response:
Nobody forbids you to do it just like you said:
class Foo {
late String foo;
String setFoo() => foo = 'foo';
}
void main() {
print(Foo().setFoo());
}
The only drawback of using the late
modifier is that you can accidentally access the foo
field before the initialization, which will cause a LateInitializationError.
To prevent this, you can use a nullable type for the field.
Moreover, you can just initialize the field inline:
String foo = 'foo';