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
Allow for shorter dot syntax to access enum values #357
Comments
This would be especially nice in collections: const supportedDirections = <CompassPoint>{.north, .east, .west};
bool isSupported = supportedDirections.containsAll({.north, .east}); It's worth noting too that we would only allow it in places where we can infer the enum type. So final north = .north; // Invalid.
final CompassPoint north = .north; // Valid.
final north = CompassPoint.north; // Valid. |
In Swift this feature works not only for enums but also for static properties of classes. See also: class Fruit {
static var apple = Fruit(name: "apple");
static var banana = Fruit(name: "banana");
var name: String;
init(name: String) {
self.name = name;
}
}
func printFruit(fruit: Fruit) {
print(fruit.name);
}
// .banana is here inferred as Fruit.banana
printFruit(fruit: .banana); |
How would the resolution work? If I write If we have a context type, we can use that as a conflict resolution: Alternatively, we could only allow the short syntax when there is a useful context type. I guess we can do that for the non-context type version too, effectively treating any self-typed static constant variable as a potential target for (Even more alternatively, we can omit the |
One approach that could be used to avoid writing |
@lrhn You may want to study how it works in Swift. I think their implementation is fine. |
If we're taking votes, I vote this ☝️ Regarding the case with void _handleCompassPoint(CompassPoint myValue) {
if (myValue == .north) {
// do something
}
}
I don't know enough about this, but I don't see why this would need to be the case if we're going with the "useful context type" only route? Right now we can do: final direction = CompassPoint.north;
print(direction == CompassPoint.south); // False.
print(direction == CompassPoint.north); // True.
print("foo" == CompassPoint.north); // False. If we know that
I don't personally prefer this approach because we risk collisions with existing in scope variable names. If someone has |
The problem with context types is that We'd have to special case equality with an enum type, so if one operand has an enum type and the other is a shorthand, the shorthand is for an enum value of the other operand's type. That's quite possible, it just doesn't follow from using context types. We have to do something extra for that. |
We can generalize the concept of "enum value" to any value or factory. If you use It still only works when there is a context type. Otherwise, you have to write the name to give context. |
To omit the FromText(
'some text',
style: FontStyle(
fontWeight: FontWeight.bold
),
), ToText(
'some text',
style: ( // [FontStyle] omitted
fontWeight: .bold // [FontWeight] omitted
),
), For enums and widgets without a constructor the FontWeight.bold -> .bold // class without a constructor
Overflow.visible -> .visible // enum
color: Color(0xFF000000) -> color: (0xFF000000) // class with constructor From issue #417_Some pints may have been presented already Not include subclasses of typeInvalidpadding: .all(10) This wont work because the type ValidtextAlign: .cener This will work because The
|
Omitting the period for constructors would lead to a whole slew of ambiguous situations simply because parentheses by themselves are meant to signify a grouping of expressions. Ignoring that, though, I think removing the period will make the intent of the code far less clear. (I'm not even sure I'd agree that this concise syntax should be available for default constructors, only for named constructors and factories.) And about the
Notice how there is no space between the
And now that there's no space between the |
A solution could be to introduce a identifyer. *.bold // example symbol But then again, that might just bloat the code/ language. |
I'd like to see something along these lines final example = MyButton("Press Me!", onTap: () => print("foo"));
final example2 = MyButton("Press Me!",
size: .small, theme: .subtle(), onTap: () => print("foo"));
class MyButton {
MyButton(
this.text, {
@required this.onTap,
this.icon,
this.size = .medium,
this.theme = .standard(),
});
final VoidCallback onTap;
final String text;
final MyButtonSize size;
final MyButtonTheme theme;
final IconData icon;
}
enum MyButtonSize { small, medium, large }
class MyButtonTheme {
MyButtonTheme.primary()
: borderColor = Colors.transparent,
fillColor = Colors.purple,
textColor = Colors.white,
iconColor = Colors.white;
MyButtonTheme.standard()
: borderColor = Colors.transparent,
fillColor = Colors.grey,
textColor = Colors.white,
iconColor = Colors.white;
MyButtonTheme.subtle()
: borderColor = Colors.purple,
fillColor = Colors.transparent,
textColor = Colors.purple,
iconColor = Colors.purple;
final Color borderColor;
final Color fillColor;
final Color textColor;
final Color iconColor;
} |
Exhaustive variants and default values are both concepts applicable in a lot of scenarios, and this feature would help in all of them to make the code more readable. I'd love to be able to use this in Flutter! return Column(
mainAxisSize: .max,
mainAxisAlignment: .end,
crossAxisAlignment: .start,
children: <Widget>[
Text('Hello', textAlign: .justify),
Row(
crossAxisAlignment: .baseline,
textBaseline: .alphabetic,
children: <Widget>[
Container(color: Colors.red),
Align(
alignment: .bottomCenter,
child: Container(color: Colors.green),
),
],
),
],
); |
Replying to @mraleph's comment #1077 (comment) on this issue since this is the canonical one for enum shorthands:
I agree that it's delightful when it works. Unfortunately, I don't think it's entirely simple to implement. At least two challenges are I know are: How does it interact with generics and type inference?You need a top-down inference context to know what f<T>(T t) {}
f(.foo) We don't know what What does it mean for enum-like classes?In large part because enums are underpowered in Dart, it's pretty common to turn an enum into an enum-like class so that you can add other members. If this shorthand only works with actual enums, that breaks any existing code that was using the shorthand syntax to access an enum member. I think that would be really painful. We could try to extend the shorthand to work with enum-like members, but that could get weird. Do we allow it at access any static member defined on the context type? Only static getters whose return type is the surrounding class's type? What if the return type is a subtype? Or we could make enum types more full-featured so that this transformation isn't needed as often. That's great, but it means the shorthand is tied to a larger feature. How does it interact with subtyping?If we extend the shorthand to work with enum-like classes, or make enums more powerful, there's a very good chance you'll have enum or enum-like types that have interesting super- and subtypes. How does the shorthand play with those? Currently, if I have a function: foo(int n) {} I can change the parameter type to accept a wider type: foo(num n) {} That's usually not a breaking change, and is a pretty minor, safe thing to do. But if that original parameter was an enum type and people were calling All of this does not mean that I think a shorthand is intractable or a bad idea. Just that it's more complex than it seems and we'll have to put some real thought into doing it right. |
If changing the interface breaks the context to the point that name inference breaks, then that is probably a good thing in the same way that making a breaking change in a package should be statically caught by the compiler. It means that the developer needs to update their code to address the breaking change. To your last example in particular foo(int n) {}
// to
foo(num n) {}
Enums don't have a superclass type, so I don't really see how an inheritance issue could arise when dealing with enums. With enum-like classes, maybe, but if you have a function that takes an enum-like value of a specific type, changing the type to a wider superclass type seems like it would be an anti-pattern anyway, and regardless would also fall into what I said earlier about implementing breaking changes resulting in errors in the static analysis of your code being a good thing. |
FWIW you list design challenges, not implementation challenges. The feature as I have described it (treat I concede that there might be some design challenges here, but I don't think resolving them should be a blocker for releasing "MVP" version of this feature. Obviously things like grammar ambiguities would need to be ironed out first: but I am not very ambitions here either, I would be totally fine shipping something that only works in parameter positions, lists and on the right hand side of comparisons - which just side steps known ambiguities.
Sometimes putting too much thought into things does not pay off because you are entering the area of diminishing returns (e.g. your design challenges are the great example of things which I think is not worth even thinking about in the context of this language feature) or worse you are entering analysis paralysis which prevents you from moving ahead and actually making the language more delightful to use with simple changes to it.
You break anybody doing this:
Does it mean we should maybe unship static tear-offs? Probably not. Same applies to the shorthand syntax being discussed here. |
I'm not a computer scientist but aren't the majority of these issues solved by making it only work with constructors / static fields that share return a type that matches the host class & enum values? That's my only expectation for it anyway, and none of those come through generic types to begin with. If the type is explicit, it seems like the dart tooling would be able to to know what type you're referring to. I don't think the value of this sugar can be understated. In the context of Flutter it would offer a ton of positive developer experience.
In the context of Flutter the missing piece that I find first is how to handle |
Yes, good point. I mispoke there. :)
That feature has caused some problems around inference, too, though, for many of the same reasons. Any time you use the surrounding context to know what an expression means while also using the expression to infer the surrounding context, you risk circularity and ambiguity problems. If we ever try to add overloading, this will be painful.
We have been intensely burned on Dart repeatedly by shipping minimum viable features:
I get what you're saying. I'm not arguing that the language team needs to go meditate on a mountain for ten years before we add a single production to the grammar. But I'm pretty certain we have historically been calibrated to underthink language designs to our detriment. I'm not proposing that we ship a complex feature, I'm suggesting that we think deeply so that we can ship a good simple feature. There are good complex features (null safety) and bad simple ones (non-shorting It's entirely OK if we think through something and decide "We're OK with the feature simply not supporting this case." That's fine. What I want to avoid is shipping it and then realizing "Oh shit, we didn't think about that interaction at all." which has historically happened more than I would like.
That's why I said "usually". :) I don't think we should unship that, no. But it does factor into the trade-offs of static tear-offs and it is something API maintainers have to think about. The only reason we have been able to change the signature of constructors in the core libraries, which we have done, is because constructors currently can't be torn off. |
For example, consider the following Flutter code: Container(
constraints: BoxConstraints.expand(
height: Theme.of(context).textTheme.headlineMedium!.fontSize! * 1.1 + 200.0,
),
padding: const EdgeInsets.all(8.0),
color: Colors.blue[600],
alignment: Alignment.center,
transform: Matrix4.rotationZ(0.1),
child: Text('Hello World',
style: Theme.of(context)
.textTheme
.headlineMedium!
.copyWith(color: Colors.white)),
) Here it would seem like the shorter dot syntax should apply to at least the |
I am sure the framework could adapt to the new feature on those specific cases. For example, one of the many alternatives is to offer: alignment: .center,
// vs
alignment: .directionalCenter, I'm sure an api could be found which would match the requirements people have And the beauty of static extensions is that if folks are unsatisfied with the current one or none is provided, they can make their own. |
It's perhaps silly, but i enjoy my code being aesthetically pleasing and sometimes e.g. when using this new switch expression with an Enum the line is too long and must be broken, but only on one line that is, not the others, symmetry is broken, and i can't use block body on the new switch expressions to fit them all in the same way, as i do with some functions, so i try to shorten variables names, but they won't fit still .. so please allow for shorter dot syntax, so my lines are not broken 🙏🥹 |
I am 100% pro this change (my second-third favorite feature after Unions and Data Class). This is a small shortcoming, but it is fine: https://twitter.com/i/web/status/1686456074034143232 Apple changed Swift's |
dart feels like a century old language to a Swift developer precisely because it lacks this feature, please make it happen |
Yeah, we would make Flutter beginner happy if docs shows like that for their first Column(
crossAxisAlignment: .stretch,
children: ...,
) |
I believe this issue is somewhat off-topic. We should avoid discussing code style, but I hope that the Dart language could provide developers with more options. If we only focus on the |
This proposal is a useful addition to the Type Inference. |
I've been looking around at some Flutter code, and from that I think there are three kinds of Dart code that this would be useful for: Enums, named constructors and static members. I'm curious to hear if others find these useful? And are there more cases to consider? EnumsExample 1: BoxFitUse current: Image(
image: collectible.icon,
fit: BoxFit.contain,
) Use desired: Image(
image: collectible.icon,
fit: .contain,
) Definitions: class Image extends StatefulWidget {
final BoxFit? fit;
const Image({
super.key,
required this.image,
...
this.fit,
});
}
enum BoxFit {
fill,
contain,
...
} Example: Example 2: AlignmentUse current: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [ ... ],
) Use desired: Row(
mainAxisAlignment: .center,
mainAxisSize: .min,
children: [ ... ],
) Definitions: class Row extends Flex {
const Row({
...
super.mainAxisAlignment,
...
}) : super(
...
);
}
class Flex extends MultiChildRenderObjectWidget {
final MainAxisAlignment mainAxisAlignment;
const Flex({
...
this.mainAxisAlignment = MainAxisAlignment.start,
...
}) : ...
}
enum MainAxisAlignment {
start,
end,
center,
...
} Example: Named constructorsExample 1: BackdropFilterUse current: BackdropFilter(
filter: ImageFilter.blur(sigmaX: x, sigmaY: y),
child: myWidget,
) Use desired: BackdropFilter(
filter: .blur(sigmaX: x, sigmaY: y),
child: myWidget,
) Definitions: class BackdropFilter extends SingleChildRenderObjectWidget {
final ui.ImageFilter filter;
const BackdropFilter({
required this.filter,
...
});
}
abstract class ImageFilter {
ImageFilter._(); // ignore: unused_element
factory ImageFilter.blur({ double sigmaX = 0.0, double sigmaY = 0.0, TileMode tileMode = TileMode.clamp }) { ... }
} Example: Example 2: PaddingUse current: Padding(
padding: EdgeInsets.all(32.0),
child: myWidget,
), Use desired: Padding(
padding: .all(32.0),
child: myWidget,
), Definitions: class Padding extends SingleChildRenderObjectWidget {
final EdgeInsetsGeometry padding;
const Padding({
super.key,
required this.padding,
super.child,
});
}
class EdgeInsets extends EdgeInsetsGeometry {
...
const EdgeInsets.all(double value)
: left = value,
top = value,
right = value,
bottom = value;
} Example: Static membersUse current: Icon(
Icons.audiotrack,
color: Colors.green,
size: 30.0,
), Use desired: Icon(
.audiotrack,
color: Colors.green,
size: 30.0,
), Definitions: class Icon extends StatelessWidget {
/// Creates an icon.
const Icon(
this.icon, {
...
}) : ... ;
final IconData? icon;
}
abstract final class Icons {
...
static const IconData audiotrack = IconData(0xe0b6, fontFamily: 'MaterialIcons');
...
} Example: |
Super useful, because there is no cognitive load to remember anything. You just press dot and wait for autocomplete to tell the options. Right now is too hard. |
Just something that came to me while reading Mit's comment is: what about when for example someone has extended For example: class EdgeInsets2 extends EdgeInsets {
const EdgeInsets2.all(super.value) : super.all();
} What would happen when we called |
@mit-mit It's about supporting values defined outside of the original class/enum, and support third-party values, such as custom colors/icons. Use current: ColoredBox(
color: Colors.red,
) Use desired: ColoredBox(
color: .red,
) Definitions: class ColoredBox extends StatefulWidget {
final Color fit;
const ColoredBox({
super.key,
required this.color,
});
}
class Color {}
// Current definition
abstract class Colors {
static final red = Color(...);
}
// After using static extensions
static extension Colors on Color {
static final red = Color(...);
} Where |
Icon would be useful, but then, how do you differentiate Material icon from something else? You can't. My fear with color is that there is no way to catch the presence of Colors |
It'd be relying on a separate highly upvoted feature: #723 Cases such as "Icon" vs "MaterialIcon" could use the same logic too. |
The same would be applied to Icons since flutter/flutter#104987 is still open. |
Yes, but it would accept IconData, not Icon, which allows Phosphor/Awesome/Other custom icons to be there. Even if material icon were an enum, it wouldn't be auto suggested because the field doesn't expect a material icon, it expects any icon. |
Static extensions can once again be used: class IconData {}
static extension Icons on Icon {
static final abc = IconData(...);
}
void main() {
Icons.abc; // valid;
IconData.abc; // also valid
// And with enum shorthands:
IconData icon = .abc; // valid too. Unwraps to `IconData.abc`
} It's the same as with Colors in the end And the key part is that it enables folks to define their own icons/colors if they wish to. For example one could use FontAwesome and define: static extension FontAwesomeIcons on IconData {
static final faMicroship = IconData(0xf2db, fontFamily: 'font-awesome');
}
...
Icon(.faMicroship); |
How would it know which one to import when the names collide? |
That's probably better discussed in #723. |
This one I don't like, because there is no way to not have the native things (Icon, Color, etc), so you would always have a conflict when using something else. You would end being even more forced to use the native Icons than right now. Would be useful if MaterialIcon(.favorite), but then kind of kills the simplification of Icon(Icons.favorite). But with everything else I fully agree. |
I believe it would be better to have the analyzer do it's job and tell you that you have conflicting options. So you would need to solve that prior to building (of course that could be also a building error). This way it could show what conflicting options there were, just like when you have two classes with the same name from different sources and it shows us what is conflicting. |
@mit-mit, those use cases are very useful! Just one little thing: It looks like the 'Static Members' example is a copy of the first example, and there's nothing in this example that involves static members (other than the fact that every enum value is compiled into a |
Sorry about that, fixed! |
Let's get this merged already!;) |
An additional use case that should be taken into account when considering this Dart language improvement is the usage of code-generated protobuf enums in Dart (CC @jacob314). These generated enum types can become very long in Dart, especially when you’re working with protobuf enums that have definitions that are nested within a message type. Borrowing the following protocol buffer enum example from the Dart protobuf documentation: message Bar {
enum Color {
COLOR_UNSPECIFIED = 0;
COLOR_RED = 1;
COLOR_GREEN = 2;
COLOR_BLUE = 3;
}
} Usage of the first enum field in Dart post-codegen currently looks like |
When using enums in Dart, it can become tedious to have to specify the full enum name every time. Since Dart has the ability to infer the type, it would be nice to allow the use of shorter dot syntax in a similar manner to Swift
The current way to use enums:
The proposed alternative:
The text was updated successfully, but these errors were encountered: