-
Notifications
You must be signed in to change notification settings - Fork 205
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
More capable Type
objects
#4200
Comments
That sounds like a Kotlin companion object.
Can we have class C {
// Before any static member:
static class extends A.class with HelperMixin1 implements HelperType2;
// Following static members are membes of this static class.
} and you can access the type as You can only extend or implement a
We probably still want to ensure that tear-offs from a static-member type is a canonicalized constant. Somehow. (That's one of the reasons I don't want normal classes to be able to implement the special singleton classes.) To make this equivalent to the current behavior, I assume constructors have access to the type parameters of the (Also, it's currently possible to have
Rather than needing this intersection, just let the generated mixin be
Probably want both a non-static and static type bound, say This will be yet another reason to allow static and instance members with the same name. How will this interact with So, dynamic x;
// ...
... (Object? o) {
...
x = o.runtimeType;
...
...
x.foo(); we may have to retain a lot of static methods that could be tree-shaken today, because we can't tell statically whether they're invoked or not. |
print((int).runtimeType); // _Type
print((int).runtimeType.runtimeType); // _Type
print((String).runtimeType); // _Type But... if (I think, the explanation is that Maybe a function like |
I would say that Then Or maybe that's a bad idea, because of what it does to tree shaking. That is:
A generic type's class objects have instances for each instantiation, and the constructor members can access those. The getters and setters of static variables are not represented by instance variables, they all access the same global variable's state. |
Great comments and questions, @lrhn!
It's similar to Kotlin (and Scala) companion objects, but also different in other ways: I'm not suggesting that Dart classes should stop having the static members and constructors that we know today, I'm just proposing that we should allow developers to request access to some of the static members and constructors (determined by the interface of the This differs from the companion objects in that there is no support for obtaining a companion object from a given actual type argument (because the type argument was erased). In contrast, a Dart type argument will always be able to deliver the corresponding For example: abstract class A<X> { X call(); }
class B1 static implements A<B1> {}
class B2 {}
void main() {
var type = someExpression ? B1 : B2;
if (type is A) {
var newObject = type();
}
} This means that the Kotlin/Scala developer must predict the need to invoke static members or constructors up front (when the concrete type is known) and must pass a reference to the required companion object(s) along with the base data. In contrast, Dart programs can pass type arguments along in the same way they do today, and then it will be possible to get access to the static members and constructors arbitrarily late, as long as the given type is available as the value of a type parameter. In the case where a class does not have a
This seems to imply that we would implicitly generate a static member or a constructor from the instance method implementations. This may or may not be doable, but I'm not quite sure what the desired semantics should be. When it comes to code reuse I would prefer to have good support for forwarding, possibly including some abstraction mechanisms (such that we could introduce sets of forwarding methods rather than specifying them one by one). This could then be used to populate the actual class with actual static members as needed, such that it is able to have the desired
I think the current approach to constants based on constructors and static members is working quite well. The ability to access static members and constructors indirectly via a reified type is an inherently dynamic feature, and I don't think it's useful to try to shoehorn it into a shape where it can yield constant expressions. There's no point in abstracting over something that you already know at compile time anyway.
Good point! Done.
I'm not quite sure what In that case,
A class that doesn't have a A class that does have a static implements clause makes some of its static members and constructors callable from the implicitly generated forwarding instance members, but this is no worse than the following: class A {
static int get foo => 1;
}
class B {
void foo() {
print(A.foo);
}
} We may still be able to detect that With "more capable It may be harder, but it does sound like a task whose complexity is similar to that of tracking invocations of instance members. That is, if we're able to determine that |
@tatumizer wrote:
If you evaluate a type literal (such as In particular, it is certainly possible for an implementation to evaluate Those reified objects may then have different interfaces, that is, they support invocations of different sets of members, so certainly it's possible for On the other hand, the reified There's nothing special about this (and that's basically the point: I want this mechanism to use all the well-known OO mechanisms to provide flexible/abstract access to the static members and constructors which are otherwise oddly inflexible, from an OO perspective).
If we have So we can certainly do abstract interface class MyInterface {
int get foo;
}
class D static implements MyInterface {
static int get foo => 1;
}
void f<X extends D>() {
var reifiedX = X;
if (reifiedX is MyInterface) {
print(reifiedX.foo);
}
} |
Could the following code similar to C#'s syntax: abstract class Json {
static fromJson(Map<String, dynamic> json);
Map<String, dynamic> toJson();
}
class User implements Json { ... } be syntatic sugar for this proposal's syntax? abstract class Json$1 {
Map<String, dynamic> toJson();
}
abstract class Json$2 {
fromJson(Map<String, dynamic> json);
}
class User implements Json$1 static implements Json$2 { ... } To keep EDIT: I can't imagine any piece of code implementing the same interface for instance methods and static methods. However, I can imagine most use cases implementing an interface with instance methods and static methods. That's why I would prefer if instance and static interfaces were merged. |
@eernstg wrote:
This can't be! Today (An argument against |
The That doesn't mean that (I chose Spoiler: void main() {
static(C).static(C.static.static.C).static(C).static;
}
class C {
static C get static => C();
C call(Object? value) => this;
}
C static(Type value) => C();
typedef _C = C;
extension on _C {
_C get static => this;
_C get C => this;
} |
Just to clarify: speaking of Object methods, I didn't mean
That's not the reason to disqualify the word - in practice, it won't hurt anyone. Most people believe Still, it's not clear what |
Class |
If A is a regular class, we can always say Q: Can class say |
Kotlin's companion object model is worth looking into, it won't take long: https://kotlinlang.org/docs/object-declarations.html#companion-objects Main difference is that the companion object has a name and a type, and - most importantly - Kotlin has a word for it, which is (predictably) "companion object". It would be very difficult to even talk about this concept without the word, so I will use it below. The idea is that you can extract a companion object from the object, e.g., (using dart's syntax), I don't know if there's a simple way to express the same concept in dart without introducing the term "companion object". Does anyone have issues with this wording? Interestingly, you very rarely need to extract the companion object explicitly, but the very possibility of doing so explains a lot: it's a real object; consequently, it has a type; this type can extend or implement other types - the whole mental model revolves around the term "companion object". |
@Wdestroier wrote:
abstract class Json {
static fromJson(Map<String, dynamic> json);
Map<String, dynamic> toJson();
}
class User implements Json { ... } Desugared: abstract class Json$1 {
Map<String, dynamic> toJson();
}
abstract class Json$2 {
fromJson(Map<String, dynamic> json);
}
class User implements Json$1 static implements Json$2 { ... } I agree with @mateusfccp that it is going to break the world if a clause like In other words, it's crucial for this proposal that abstract class StaticInterface1 { int get foo; }
abstract class StaticInterface2 { void bar(); }
class B static implements StaticInterface1 {
final int i;
B(this.i);
static int get foo => 10;
}
class C extends B static implements StaticInterface2 {
C(super.i);
static void bar() {}
} This also implies that there is no reason to assume that a type variable void f<X extends Y, Y static extends StaticInterface1>() {
Y.foo; // OK.
X.foo; // Compile-time error, no such member.
} |
I must say I am in love with this proposal. It solves many "problems" at once (although it may introduce more? let's see how the discussion goes), and it's a very interesting concept. I agree that it's not as straightforward to understand it, but once you understand, it makes a lot of sense. I also understand the appeal in having the dynamic and static interfaces bundled together, as @Wdestroier suggests, so if we could come with a non-breaking and viable syntax for doing it (while still providing the base mechanism), I think it would be valuable. |
@tatumizer wrote:
Today If you want to test whether the reified type object for void main() {
var ReifiedString = String; // Obtain the reified type object for the type `String`.
if (ReifiedString is Object) { // Same operation as `String is Object`.
// Here we know that `ReifiedString` is an `Object`, but
// we knew that already, so we can't do anything extra.
ReifiedString.toString(); // Can do, not exciting. ;-)
}
} Testing that It's the instance members of the tested type This means that if The reason why I'm emphasizing that it's all about instance members is that we already have the entire machinery for instance members: Late binding, correct overriding, the works. The static members and the constructors are just used to derive a corresponding instance member that forwards to them, and all the rest occurs in normal object land, with normal OO semantics. |
@eernstg : I understand each of these points, but they don't self-assemble in my head to result in a sense of understanding of the whole. The problem is terminological in nature. See my previous post about Kotlin. |
About Kotlin's companion object, I already mentioned it here. The main point is that you cannot obtain the companion object based on a type argument, you have to denote the concrete class. This reduces the expressive power considerably, because you can pass the type along as a type parameter and you can pass the companion object on as a regular value object, and then you can use the type as a type and the companion object as a way to access static members and constructors of that type. This is tedious because you have to pass the type and the object along your entire call chain whenever you want to use both. You could also pass the type alone, but then you can't get hold of the companion object. Or you could pass the companion object alone, but then you can't use the type (which is highly relevant, e.g., if you're calling constructors). I spelled out how it is possible to write a companion object manually in Dart in this comment. With this proposal, we can obtain the "companion object" (that is, the reified type object) for any given type (type variable or otherwise) by evaluating that type as an expression at any time we want, and we can test whether it satisfies a given interface such that we can call the static members / constructors of that type safely. |
@tatumizer wrote:
The role of the companion object in Kotlin and Scala is played by the reified type object in this proposal. We could of course also introduce an indirection and just add a |
@eernstg : that's where I have to disagree. It's an extra step for cognitive reason, which is a hell of a reason. :-) (Main property of a companion object, apart of its very existence, is that it has a clear type, which is visibly distinct from the type of the object itself, and it's a part of an (explicitly) different hierarchy. The difference is in explicitness). |
If we just use the phrase 'companion object' rather than 'reified type object', would that suffice? I don't think there's any real difference between the members of a companion object in Scala and Kotlin, and the forwarding instance members in this proposal, so the reified type object is the companion object. There is a difference in that this proposal only populates the companion object with forwarding instance members when the target class has a We could also choose to populate every reified type object with all static members and all constructors. However, I suspect that it's a better trade-off to avoid generating so many forwarding methods because (1) they will consume resources (time and space) at least during compilation, and perhaps the unused ones won't be fully tree-shaken, and (2) they aren't recognized by the static type system if the reified type object doesn't have any useful denotable supertypes (so all invocations would then have to be performed dynamically).
Good point! It is indeed an element of implicitness that this proposal works in terms of a 1:1 connection between each targeted static member / constructor and a forwarding instance member of the reified type object. We don't have that kind of relationship anywhere else in the language. The connection is created by specifying exactly how we will take a static member declaration and derive the corresponding instance member signature, and similarly for each constructor. I don't know how this could be made more explicit without asking developers to write a lot of code that would be computed deterministically anyway (which is basically the definition of redundancy). For the type, the |
I don't know if that will suffice, but it would certainly be a step in the right direction. When I see the expression "reified type object", my head refuses to operate further - though I can guess what this means, I'm not sure the guess is correct, and the word "reified" especially scares me off (like, WTF: how this reified type object differs from just type object?). I'll respond to the rest of your comments here later, need time to process :-). |
True, it's important to be an opt-in feature. abstract class MyClass {
// No effect on subtypes.
static String name() => 'MyClass';
// Has effect on subtypes.
abstract MyClass();
// Has effect on subtypes.
abstract static MyClass fromMap(Map<String, dynamic> json) =>
MyConcreteClass(property: json['property']);
} |
Here's an arrangement I could understand:
print(String.companionObject is StringCompanion); // true
print(String.companionObject.runtimeType == StringCompanion); // true This is achieved by adding one method to the Type class: class Type {
Object companionObject; // just an Object
// etc...
}
class Foo<T static implements SomeKnownInterface> {
bar() {
T.companionObject.methodFromKnownInterface(...);
}
}
class Foo static implements FromJson<Foo> {
// no changes to the existing syntax
static Foo fromJson(String str) { ... }
} The companion object will only include the methods from the
The difference of this design and the original one is that, given a type parameter T, you can write WDYT? (Possible alternative for "companionObject": "staticInterfaceObject" or something that contains the word "static") |
Very good! I think I can add a couple of comments here and there to explain why this is just "the same thing with one extra step" compared to my proposal. You may prefer to have that extra step for whatever reason, but I don't think it contributes any extra affordances. Also, I'll try to demystify the notion of a 'reified type object'.
Right, that's exactly what I meant by 'We could of course also introduce an indirection' here.
You'd have to use print((String).companionObject is StringCompanion); // true
print((String).companionObject.runtimeType == StringCompanion); // true But the value of evaluating a type literal like The core idea in this proposal (meaning "the proposal in the first post of this issue") is that this object should (1) have instance members forwarding to the static members and constructors of the type which is being reified, and it should (2) have a type that allows us to call those static members and constructors (indirectly via forwarders) in a type safe manner, without knowing statically that it is exactly the static members and constructors of Returning to To compare, this proposal will do exactly the same thing in the following way (assuming that print(String is Interface); // true
print((String).runtimeType == Interface); // false The second query is false because the run-time type is not exactly
Here's how to do it in this proposal: class Foo<T static implements SomeKnownInterface> {
bar() {
(T).methodFromKnownInterface(...);
}
} The proposal has an extra shortcut: If we encounter
These statements are true for this proposal as well.
The corresponding statement for this proposal is that if the class doesn't declare
In your proposal you can write I hope this illustrates that the two approaches correspond to each other very precisely, and the only difference is that the |
@eernstg: I think I can pinpoint the single place where our views diverge, and it's this: |
Great, I think we're converging!
That's generally not a problem. In my proposal, the RTO for a given class has a type which is a subtype of Currently, we already have a situation where the result returned from the built-in This implies that it isn't a breaking change to make those evaluations yield a result whose type isn't Next step, the static type of an expression that evaluates a type literal that denotes a class/mixin/etc. declaration can include the meta-member mixin. In other words, the static type of This implies that we can safely assign this RTO to a variable with the abstract class StaticFooable { void foo(); }
class A static implements StaticFooable {
static void foo() => print('A.foo');
}
void main() {
StaticFooable companion = A;
companion.foo(); // Prints 'A.foo'.
} However, we can not use an overriding declaration of This means that we don't know anything more specific than It might seem nice and natural if we could make the static interface co-vary with the interface of the base object itself (such that we could use However, note that it would certainly be possible for a type argument to use subsumption in static interface types: abstract class StaticFooable { void foo(); }
abstract class StaticFooBarable implements StaticFooable { void bar(); }
class B extends A static implements StaticFooBarable {
static void foo() => print('B.foo');
static void bar() => print('B.bar');
}
void baz<X static extends StaticFooable>() {
X.foo(); // OK
X.bar(); // Compile-time error, no such member.
(X as dynamic). bar(); // Succeeds when `X` is `B`.
}
void main() {
baz<B>(); // OK, `StaticFooBarable <: StaticFooable` implies that `B is StaticFooable`.
} |
Why do you need this Compare with this: we can declare some method as returning To be sure if we are on the same page, please answer this question. The static type of expression (After re-reading your response, I am not even sure we disagree on anything important, And I do acknowledge the benefits of your proposal, assuming we agree that |
After considering it more, the idea of including in RTO only the references to methods from the declared static interfaces might be unnecessary. Whenever the tree-shaker decides to preserve class C, it will most likely have to preserve its noname constructor, too (otherwise, no one can create an instance). Apart from constructors, the classes rarely have static methods, and those that are potentially used could be identified by name (e.g. if someone says Another point: I think static interfaces don't make much sense. I can't imagine the situation where a class expects type parameter to implement some static methods without also expecting the instances to implement some specific regular methods. abstract class Ring<T> {
abstract T operator+(T other);
abstract T operator*(T other);
// ...etc
abstract static T zero; // SIC!
abstract static T unity;
}
class Integer implements Ring<Integer> {
final int _n;
Integer(this._n);
// ...implementation of operators,
static const zero = Integer(0);
static const unity = Integer(1);
} |
At the risk of this having already been explained and not getting the syntax right, I have a couple questions: abstract class A<X> {
int get foo;
void bar();
X call(int _);
X named(int _, int _);
bool operator==(Object other) {
return other is A && foo == other.foo;
}
}
class B static implements A<B> {
final int i;
B(this.i);
B.named(int i, int j): this(i + j);
static int get foo => 1;
static void bar() {}
}
class C implements A<C> {
const C(this.foo);
@override
final int foo;
@override
void bar() {}
@override
C call(int _) => this;
@override
C named(int _, int _) => this;
}
void main() {
assert(B(0).runtimeType == const C(1));
} would that be legal? And would it be possible for a class to both implement and static implement the same class at the same time? If the name conflict can / could be somehow avoided? And is the override annotation not required / recommended for static implements? sealed class A<X> {
int get foo;
void bar();
X call(int _);
X named(int _, int _);
}
class B static implements A<B> {
final int i;
B(this.i);
B.named(int i, int j): this(i + j);
static int get foo => 1;
static void bar() {}
}
void main() {
final (A) t = B;
final _ = switch(t) {
const (B) _ => print("b"),
// I have to exhaustively check for all classes that static implement A
};
} And would something like that be possible? |
@tatumizer wrote, about my remark that one might want to override the return type of
Agreed. It's common and useful to override a return type covariantly, but it won't work in this case, that's all I wanted to say. Here's an outline of a case where it does work: abstract class A {
List<A> get selfInList;
}
class B1 implements A {
List<B1> get selfInList => [this]; // Override the return type covariantly.
void b1Thing() {}
}
class B2 implements A {
List<B2> get selfInList => [this]; // Many subtypes of `A` could do this.
}
void main() {
var b1 = B1();
b1.selfInList[0].b1Thing(); // Only type correct because of the covariant override.
} The reason why it will not work with the "more capable
No. class A {
void foo() {}
}
class B {
void bar();
Type get runtimeType => A;
}
void main() {
assert(A().runtimeType == B().runtimeType);
} We do have that property, though, if it is guaranteed that
I thought so, too! 😄
Sounds good! We're in control as developers for these things: If
That's different, I think it's crucial that type literals have the best possible type, and in particular that they must have a static type that includes the static interface. So if class FooStaticInterface {
void staticMethod(int i) {}
}
class Foo static implements FooStaticInterface {...}
class Bar static implements FooStaticInterface {...}
void main() {
var metaObject = someCondition ? Foo : Bar;
metaObject.staticMethod(); // Statically typed and safe.
} |
@tatumizer wrote:
We should most likely be able to specify both, independently. abstract class StaticRingInterface<T> {
T get zero;
T get unity;
}
abstract class Ring<T> static implements StaticRingInterface<T> {
abstract T operator+(T other);
abstract T operator*(T other);
// ...etc
abstract static T zero; // SIC!
abstract static T unity;
}
class Integer implements Ring<Integer> static implements StaticRingInterface<Integer> {
final int _n;
Integer(this._n);
// ...implementation of operators,
static const zero = Integer(0);
static const unity = Integer(1);
}
void useIt<R extends Ring<R> static extends StaticRingInterface<R>>(R r) {
var same = r * R.unity + R.zero;
} |
@eernstg: thanks! it would take a while for me to comprehend this abstract class FromJson<T> {
static abstract T fromJson(String str);
}
class Foo implements FromJson<Foo> {
static Foo fromJson(String str) {...}
} I mean, the concept would be much nicer with |
@benthillerkus wrote:
about the following (I added some comments): abstract class A<X> {
int get foo;
void bar();
X call(int _);
X named(int _, int _);
// Comment 1 below.
bool operator ==(Object other) {
return other is A && foo == other.foo;
}
}
class B static implements A<B> {
final int i;
B(this.i);
B.named(int i, int j): this(i + j);
static int get foo => 1;
static void bar() {}
}
// Comment 2.
class C implements A<C> {
const C(this.foo);
@override
final int foo;
@override
void bar() {}
@override
C call(int _) => this;
@override
C named(int _, int _) => this;
}
void main() {
// Comment 3.
assert(B(0).runtimeType == const C(1));
}
Possible (if we can avoid name clashes and other errors), but probably silly. ;-) I can't come up with a situation where this would be useful.
It could certainly be supported: class B static implements A<B> {
final int i;
@override
B(this.i);
@override
B.named(int i, int j): this(i + j);
@override
static int get foo => 1;
@override
static void bar() {}
} The metadata on constructors and static members would go together with having a On the other hand, it's probably more readable if this task is handled by a new value, say, In any case, it would be recommended to have it on all the constructors / static members which are needed in order to satisfy the given |
@tatumizer wrote:
I think it's implied that any In particular, constructors wouldn't fit in with this concept. I'd expect that different classes have different constructors, and it would be highly impractical to say that "each of the subclasses Another difficulty is that it is unobvious (to me, at least) how we would be able to model the typing of constructors: They return something which is basically the |
@eernstg: class A<T> {
foo() {
if (T is SomeStaticInterface) {...}
}
} Question: can we find out whether the objects of type T implement some regular interface Foo? I made an effort to understand the example of
Sure, they do not co-vary automatically. But my point is that the mechanism of abstract static methods will FORCE them to co-vary (or, rather, force the author to co-vary them). Without this co-variance, the matters will become very complicated, and the mechsnism will not be used to its full potential out of fear of misunderstanding. To illustrate: abstract class HasFromJson<Self> {
static abstract /* exactly?*/ Self fromJson(String str);
// for illustration only, I include ALSO a normal method
abstract void foo();
}
class Point implements HasFromJson<Point> {
final int x, y;
Point(this.x, this.y);
foo() {} // foo implemented
static Point fromJson(String str) { /* code */}
}
class ColorPoint extends Point { // maybe ERROR: should implement HasFromJson<ColorPoint> - not sure
final int color;
ColorPoint(super.x, super.y, this.color);
// ERROR: static method fromJson not implemented
} Here, the compiler will notice that ColorPoint is missing an implementation of fromJson and force the user to write it. (The method Do you see any problem with the implementation of this mechanism? (I can argue that even a "plain" method |
When bool typeArgumentIsFoo<T>() => <T>[] is List<Foo>;
// We can test against non-constant types as well.
bool typeArgumentsAreIncreasing<X, Y>() => <X>[] is List<Y>; This is somewhat costly because we're creating a new list just to test the subtype relationship between two types, but it works, and it is relatively easy to do (and remember ;-). If we only have the reified type object (an instance of We could have a feature like bool reifiedTypeObjectIsFoo<X>() => X is Type<Foo>; The
This could be a nice feature to have when we're considering client code where the RTOs are being used (we'd just have However, I'm not convinced that it is possible in practice. I suspect that the static interfaces of classes/mixins/etc in a subtype hierarchy will be independent rather than covarying, and it's going to make the feature considerably less helpful if you must follow that discipline for the static members and constructors of all subtypes. On the other hand, I did consider having an opt-in mechanism along these lines: We could have a abstract class A<X> {
int get foo;
void bar();
X call(int _);
X named(int _, int _);
}
class B covariant static implements A<B> {
final int i;
B(this.i);
B.named(int i, int j): this(i + j);
static int get foo => 1;
static void bar() {}
}
class C extends B static implements A<C> {
C(super.i);
C.named(int i, int j): super.named(j, i + j);
static get foo => 2;
// `static void bar() => B.bar();` implicitly induced (that is, "`bar` is inherited").
} This would work, and it might be nice to have, but the verbosity of |
Indeed! It's the 5th time that I have learned about this trick, and each time I wonder how cute and easy-to-remember it is 😄
But I suspect the contrary is true! Deep subtype hierarchies are out of fashion. Some languages don't support hierarchies at all - everything is done through the interfaces. Even if subclassing is supported, people still tend to avoid deep hierarchies. Flutter declares on page one that all the hierarchies are shallow and posits that as a big plus. We need some data points here. If it turns out that the interface and hypothetical static interface in practice co-vary in the cases of the hierarchy depth=2, then any further generalization doesn't make practical sense. But the cognitive/usability cost of such generalization is high: the difference in user's perception of the feature would be between "WOW" for one design and "WTF" for another. In any case, I guess the language can always create a view for the user where all the information about interfaces, static interfaces and what-not seems to be encapsulated in the RTO. By overriding "runtimeType", the system can pretend each RTO has an intelligible type name (it can be a private WDYT? (I googled around about the use cases for abstract static methods in C#. They are few and far between. The major motivation for a feature is an abstraction of numbers like |
I think deep subtype hierarchies were basically always less than optimal. Aside: I guess we should call them subinterface hierarchies in Dart because it's all about nominally introduced subtyping (
I don't think it matters whether a superinterface is reached via an Granted, a very deep superinterface graph could be even harder to reconcile with the "static interface must co-vary" requirement than a shallow one. I just think it might be sufficiently inconvenient already with a shallow one.
+100.
Not surprising. I would assume that operators play a very important role here because we might want to abstract over them (such that we can have However, cases like One thing which may be worth noting is that |
@eernstg: I don't know how C# handles this, and know even less about how dart is going to do it. 😄 (BTW, I don't even know how to implement |
I'd expect So the interesting part would be This member needs to be a constructor, or it needs to be We could use the abstract class FromJson<X> {
X fromJson(Map<String, dynamic>);
}
class Point static implements FromJson<Point> {
final int x, y;
Point(this.x, this.y);
Point.fromJson(Map<String, dynamic> map): this(map["x"], map["y"]);
}
class ColorPoint extends Point static implements FromJson<ColorPoint> {
final String color;
ColorPoint(super.x, super.y, this.color);
ColorPoint.fromJson(Map<String, dynamic> map): this(map["x"], map["y"], map["color"]);
}
X create<X extends Object>(FromJson<X>> type, Map<String, dynamic> map) {
return type.fromJSon(map);
}
void main() {
var pointMap = {"x": 3, "y": 4};
var colorPointMap = {"x": 3, "y": 4, "color": "blue"};
// Basic approach: Just use the constructors directly when we know the type.
var p1 = Point.fromJson(pointMap); // OK, `p1` has type `Point`.
var p2 = ColorPoint.fromJson(colorPointMap); // OK, type `ColorPoint`.
// `create` can use a reified type object.
var p3 = create(Point, pointMap); // Type `Point`.
var p4 = create(ColorPoint, colorPointMap); // Type `ColorPoint`.
// `create` can also work on the reified type object under a more general type.
FromJson<Object> type = Point;
var p5 = create(type, colorPointMap); // Static type `Object`, dynamic `Point`.
type = ColorPoint;
var p6 = create(type, colorPointMap); // Static type `Object`, dynamic `ColorPoint`.
// Finally, we can of course rediscover the type.
if (type is FromJson<ColorPoint>) {
var p7 = type.fromJson(colorPointMap); // Type `ColorPoint` again, static and dynamic.
}
} At the end we're using This is an example where we really need to avoid the constraint that the static interface must co-vary with the instance interface: Considering your example, if we're forced to have But it's no problem to have Instead, it is the reified type object for It would even be OK to have X create2<X extends Point>(Map<String, dynamic> map) {
return X.fromJson(map);
} |
Apparently, I failed to formulate the question clearly. The class When we create a ColorPoint as a subclass of Point, this ColorPoint, in turn, should either implement BOTH methods, or none - these methods cannot be separated from each other. ColorPoint should not even inherit toJson from Point - for, with such a blind inheritance, it will miss abstract noninherited interface JsonSupport<T> {
abstract Map<...> toJson();
abstract static T fromJson(Map<...> json);
} The bottom line: static methods are "entangled" with the instance methods resulting in a single indivisible concept. This is what happens in the case of abstract numbers: "zero" and "unity" are entangled with the operators And that's exactly why C# approach (allowing the combination of instance and static methods defined in the same interface) is the right one. Interestingly, as soon as we agree that the interface can be marked as non-inherited, the whole "issue" of co-variance just goes away. Nothing really "varies" any longer 😄 (Using covariant/contravariant/invariant terminology, "noninherited" becomes "nonvariant") |
Isn't it enough to annotate Also I don't think |
No, toJson doesn't have to be overridden, and if it IS "overridden", it has to be "overridden" together with
It's not "bad". It belongs to the category of "not even wrong" IMO 😄 |
(@benthillerkus, it looks like we landed at the same spot. ;-) @tatumizer wrote:
My immediate take on this is "Sure, no problem": abstract class FromJson<X> {
X fromJson(Map<String, dynamic>);
}
abstract class ToJson {
Map<String, dynamic> toJson();
}
class Point implements ToJson static implements FromJson<Point> {
final int x, y;
Point(this.x, this.y);
Point.fromJson(Map<String, dynamic> map): this(map["x"], map["y"]);
Map<String, dynamic> toJson() => {"x": x, "y": y};
}
class ColorPoint extends Point static implements FromJson<ColorPoint> {
final String color;
ColorPoint(super.x, super.y, this.color);
ColorPoint.fromJson(Map<String, dynamic> map): this(map["x"], map["y"], map["color"]);
Map<String, dynamic> toJson() => {"x": x, "y": y, "color": color};
}
X create<X extends Object>(FromJson<X> type, Map<String, dynamic> map) {
return type.fromJSon(map);
}
void main() {
var pointMap = Point(3, 4).toJson();
var colorPointMap = ColorPoint(3, 4, "blue").toJson();
// Basic approach: Just use the constructors directly when we know the type.
var p1 = Point.fromJson(pointMap); // OK, `p1` has type `Point`.
var p2 = ColorPoint.fromJson(colorPointMap); // OK, type `ColorPoint`.
// `create` can use a reified type object.
var p3 = create(Point, pointMap); // Type `Point`.
var p4 = create(ColorPoint, colorPointMap); // Type `ColorPoint`.
// `create` can also work on the reified type object under a more general type.
FromJson<Object> type = Point;
var p5 = create(type, colorPointMap); // Static type `Object`, dynamic `Point`.
type = ColorPoint;
var p6 = create(type, colorPointMap); // Static type `Object`, dynamic `ColorPoint`.
// Finally, we can of course rediscover the type.
if (type is FromJson<ColorPoint>) {
var p7 = type.fromJson(colorPointMap); // Type `ColorPoint` again, static and dynamic.
}
}
I'm arguing that this will not work. So I wouldn't be surprised if we could find further difficulties with that.
I don't understand why that constraint would be needed, neither technically nor conceptually. I put them into different abstract class declarations because they need to be treated very differently: One is a plain instance method, easy to handle in every way that I can think of. The other one inherently has no existing instance of the target class to rely on so it must be a static method, and this creates a lot of difficulties with abstraction and subtyping (and this entire issue is basically an attempt to improve on that). Finally, those two methods do not depend on each other.
This could be turned into a language feature (I think I proposed that, several years ago). But it's kind of a lint because there's nothing that goes wrong technically if But you can't turn every bug into a compile-time error, and it smells like this is an instance of that.
I don't understand why that would be true. Covariance is a relationship whereby some entity works like a monotone (that is, an increasing) function. So In this case the covariance constraint would be applied to static members (and constructors?): // Assume that the static interface is subject to "correct override" checks,
// that is, it must co-vary.
class A {
static num get foo => 1;
static num get bar => 1;
}
class B implements A {
static int get foo => 2; // OK.
static String get bar => 'Hello!'; // Error.
} If we want to support subsumption at the static level then we'd allow But there's no way we can claim that Hence, I just can't see how a |
To resolve the conceptual difficulties you mentioned, we can establish a different view on the methods like toJson. I have an impression from your posts that somehow you find it logical that as soon as we put 2 static methods in the same (static) interface, and make the class implement this interface, then the methods become the subject to inheritance. Why? A single static method is not inherited, but two of them are? In principle, we could avoid placing a mix of static and instance methods into the same interface if we convert the methods like toJson into their static equivalent manually , but if we have operators as part of such an interface, there's no syntax for that in dart (in other languages, there is). The "instance" form of invocation for such methods in just a syntactic convenience - in fact, they are static methods. In which case it goes without saying they are not subject to inheritance. |
This issue is a response to #356 and other issues requesting virtual static methods or the ability to create a new instance based on a type variable, and similar features.
Static substitutability is hard
The main difficulty with existing proposals in this area is that the set of static members and constructors declared by any given class/mixin/enum/extension type declaration has no interface and no subtype relationships:
As a fundamental OO fact,
B
is an enhanced version ofA
when it comes to instance members (even in this case where we don't enhance anything), but it is simply completely unrelated when it comes to constructors and static members.In particular, the relationship between the constructors
A();
andB();
is very different from an override relationship.A
has a constructor namedA.named
butB
doesn't have a constructor namedB.named
. The static memberB.foo
does not overrideA.foo
.B
does not inheritA.bar
. In general, none of the mechanisms and constraints that allow subtype substitutability when it comes to instance members are available when it comes to "class members" (that is, static members and constructors).Consequently, it would be a massively breaking change to introduce a rule that requires subtype substitutability with respect to class members (apart from the fact that we would need to come up with a precise definition of what that means). This means that it is a highly non-trivial effort to introduce the concept which has been known as a 'static interface' in #356.
This comment mentions the approach which has been taken in C#. This issue suggests going in a different direction that seems like a better match for Dart. The main difference is that the C# approach introduces an actual static interface (static members in an interface that must be implemented by the class that claims to be an implementation of that interface). The approach proposed here transforms the static members into instance members, which means that we immediately have the entire language and all the normal subsumption mechanisms, we don't have to build an entirely new machine for static members.
What's the benefit?
It has been proposed many times, going back to 2013 at least, that an instance of
Type
that reifies a classC
should be able to do a number of things thatC
can do. E.g., if we can doC()
in order to obtain a new instance of the classC
then we should also be able to doMyType()
to obtain such an instance when we havevar MyType = C;
. Similarly forT()
whenT
is a type variable whose value isC
.Another set of requests in this topic area is that static members should be virtual. This is trivially true with this proposal because we're using instance members of the reified
Type
objects to manage the access to the static members.There are several different use cases. A major one is serialization/deserialization where we may frequently need to create instances of a class which is not statically known, and we may wish to call a "virtual static method".
Proposal
We introduce a new kind of type declaration header clause,
static implements
, which is used to indicate that the given declaration must satisfy some subtype-like constraints on the set of static members and constructors.The operand(s) of this clause are regular class/mixin/mixin-class declarations, and the subtype constraints are based on the instance members of these operands. In other words, they are supertypes (of "something"!) in a completely standard way (and the novelty arises because of that "something").
The core idea is that this "something" is a computed set of instance members, amounting to a correct override of each of the instance members of the combined interface of the
static implements
types.These declarations have no compile-time errors. The static analysis notes the
static implements
clause, computes the corresponding meta-member for each static member and for each constructor, and checks that the resulting set of meta-members amount to a correct and complete set of instance members for a class that implementsA<B>
. Here is the set of meta-members (note that they are implicitly created by the tools, not written by a person):The constructor named
B
becomes an instance method namedcall
that takes the same arguments and returns aB
. Similarly, the constructor namedB.named
becomes an instance method namednamed
. Static members become instance members, with the same name and the same signature.The point is that we can now change the result of type
Type
which is returned by evaluatingB
such that it includes this mixin.This implies that for each constructor and static member of
B
, we can call a corresponding instance member of itsType
:This shows that the given
Type
object has the required instance members, and we can use them to get the same effect as that of calling constructors and static members ofB
.We used the type
dynamic
above because those methods are not members of the interface ofType
. However, we could change the typing of type literal expressions such that are not justType
. They could beType & M
in every situation where it is known that the reified type has a given mixinM
. We would then be able to use the following typed approach:Next, we could treat members invoked on type variables specially, such that
T.baz()
means(T).baz()
. This turnsT
into an instance ofType
, which means that we have access to all the meta members of the type. This is a plausible treatment because type variables don't have static members (not even if and when we get static extensions), soT.baz()
is definitely an error today.We would need to consider exactly how to characterize a type variable as having a reified representation that has a certain interface. Perhaps we could use the following:
Even if it turns out to be hard to handle type variables so smoothly, we could of course test it at run time:
Revisions
on Type
.The text was updated successfully, but these errors were encountered: