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'
2条答案
按热度按时间i7uq4tfw1#
我想我找到了,也就是说,对于foo可以为null的情况:
ct3nt3jp2#
没有人禁止你这样做,就像你说的:
使用
late
修饰符的唯一缺点是,您可能会在初始化之前意外访问foo
字段,这将导致LateInitializationError。为了防止这种情况,您可以为该字段使用可为null的类型。此外,您可以直接初始化内联字段: