Are there any plans to introduce attributes
for classes, methods, parameters of methods,
something like C# or Java attributes ?
[Test]
class SomeClass
{
[Test]
someMethod()
}
or
#Test
class SomeClass
{
#Test
someMethod(#Test int param)
}
For many frameworks it would be very useful
In dart, they are called metadata / annotation. The syntax is quite close to java. Here's a example :
#Test testMethod() {}
In Dart Specification you can read :
Metadata consists of a series of annotations, each of which begin with the character #, followed a constant expression that starts with an identifier. It is a compile time error if the expression is not one of the following:
A reference to a compile-time constant variable.
A call to a constant constructor.
[....]
Metadata can appear before a library, class, typedef, type parameter, constructor, factory, function, field, parameter, or variable declaration and before an import or export directive.
There're already some annotations predifined in dart:core. Particulary #override, #deprecated and #proxy.
Dart already has annotations, similar to Java in some ways, they're just not used in very many places yet, and they're not accessible from reflection yet either.
See this article: http://news.dartlang.org/2012/06/proposal-to-add-metadata-to-dart.html
Here's a brief introduction to the two metadata annotations currently available in the Dart meta library:
Dart Metadata is your friend.
This doesn't preclude you from using your own, but these are the two that have tooling integration with the Dart Editor.
Related
I'm new to dart and came across code like below:
class Foo {
Foo._internal();
static final Foo instance = Foo._internal();
// other stuff
}
I was confused by that the function _internal is called twice(in line2 and line3 respectively).
Later I realized the first one is actually not an invocation but a definition of a constructor.
It's just that the body of the definition is omited(allowing this is really bad a syntax rule of Dart IMHO).
So my question become that in what cases a function of dart can omit body?
Dart provides a lot of syntactic sugar for constructors, including the ability to use a semicolon in place of an empty constructor body. Since initialization lists should be preferred when possible, it's not uncommon for constructors to have empty bodies, so the shorthand is useful. Additionally, redirecting constructors and const constructors aren't allowed to have bodies at all.
Constructors aren't functions, so that shorthand does not apply to functions and methods in general. (As another example of a distinction between constructors and functions, only constructors can be used with new and const.) For methods, distinguishing between no body and an empty body is important:
abstract class AbstractInterface {
void mustBeOverridden();
void optionallyOverridden() {}
}
I agree that a constructor like Foo._internal(); looks weird, but I think it's not a common situation since it requires the intersection of a number of cases to make it look like a method call:
The class uses a named constructor.
That constructor takes no arguments.
That constructor does not use an initializer list.
That constructor does not use a constructor body.
A common question, specifically since Dart 2, is if it is possible to require some or all generic type arguments on some or all types - for example List<int> instead of List or MyType<Foo> instead of MyType.
It's not always clear what the intention is though - i.e. is this a matter of style (you/your team likes to see the types), to prevent bugs (omitting type arguments seems to cause more bugs for you/your team), or as a matter of contract (your library expects a type argument).
For example, on dart-misc, a user writes:
Basically, if I have this:
abstract class Mixin<T> {}
I don't have to specify the type:
// Works class Cls extends Object with Mixin<int> {} // ...also works
class Cls extends Object with Mixin {}
Is there some way to make the second one not allowed?
Strictly speaking, yes, and no.
If you want to enforce that type arguments are always used in your own projects (instead of relying on type inference or defaults), you can use optional linter rules such as always_specify_types. Do note this rule violates the official Dart style guide's recommendation of AVOID redundant type arguments on generic invocations in many cases.
If you want to enforce that generic type arguments are always used when the default would be confusing - such as List implicitly meaning List<dynamic>, no such lint exists yet - though we plan on adding this as a mode of the analyzer: https://github.com/dart-lang/sdk/issues/33119.
Both of the above recommendations will help yourself, but if you are creating a library for others to use, you might be asking if you can require a type argument to use your class. For example, from above:
abstract class Mixin<T> {}
abstract class Class extends Object with Mixin {}
The first thing you could do is add a default bounds to T:
// If T is omitted/not inferred, it defaults to num, not dynamic.
abstract class Mixin<T extends num> {}
If you want to allow anything but want to make it difficult to use your class/mixin when T is dynamic you could choose a different default bound, for example Object, or even better I recommend void:
In practice, I use void to mean “anything and I don’t care about the elements”
abstract class Mixin<T extends void> {
T value;
}
class Class extends Mixin {}
void main() {
var c = Class();
// Compile-time error: 'oops' isn't defined for the class 'void'.
c.value.oops();
}
(You could also use Object for this purpose)
If this is a class under your control, you could add an assertion that prevents the class from being used in a way you don't support or expect. For example:
class AlwaysSpecifyType<T> {
AlwaysSpecifyType() {
assert(T != dynamic);
}
}
Finally, you could write a custom lint or tool to disallow certain generic type arguments from being omitted, but that is likely the most amount of work, and if any of the previous approaches work for you, I'd strongly recommend those!
In many languages if you try to instantiate abstract class you get compile time error.
In Dart however, you get warning while compiling and a runtime exception AbstractClassInstantiationError.
Why is that? Can someone provide an example, where it's reasonable to compile such code?
Dart tries to allow you to run your program while you are developing it.
That is why many things that are compile time errors in other languages are compile-time warnings and runtime errors in Dart. This includes "x is Foo" where Foo doesn't exist, type-annotating with a non-existing types, and calling constructors of partial (abstract) classes.
In short: because it's not a problem that prevents the program from being compiled (unlike a syntax error that might mean the rest of the file is interpreted wrongly), so there is no reason to stop you from running the code. Only if you hit the branch that actually depends on the problem will your program be stopped.
It appears that the answer is factory constructor in abstract class:
abstract class Foo {
factory Foo() { // make Foo appear to be instantiable
return new Bar();
}
some(); // some abstract method
Foo.name() {} just a named constructor
}
class Bar extends Foo {
Bar():super.name(); // call named super constructor
some() {} // implement abstract method
}
main() {
print(new Foo()); // "instantiate" abstract Foo
}
Output:
Instance of 'Bar'
Asking 'where it's reasonable to compile such code?' in Dart isn't very meaningful because Dart is an interpreted language - there is no compilation stage. Dart editors will issue warnings if they think you are making a type error as they analyse your code on the fly.
Factory constructors can be used to provide a 'default' concrete implementation of an abstract class as you have done in your example. This is used quite widely in Dart. For instance, if you create a new Map object you actually get a LinkedHashMap object - see this question and answer.
In your example your are not instantiating an instance of Foo ('new Foo' does not appear anywhere), you are instantiating a `Bar'. This is because when a factory constructor is called a new instance of its class is not automatically instantiated.
What does external mean in Dart? For example: external DateTime._now();
I'm new to Dart, I can't find documentation for external, so can you give an example to help explain?
9.4 External Functions
An external function is a function whose body is provided separately from its
declaration. An external function may be a top-level function (17), a method
The body of the function is defined somewhere else.
As far as I know this is used to fix different implementations for Dart VM in the browser and Dart VM on the Server.
When we make an external function inside a class like toString()
external String toString();
means this method is abstract and the child of the parent class will add the function body, that's because in Dart we only can make an abstract class.
Summary:
external function = abstract function in not abstract classes
I don't think external keyword is meant to be used to mark methods as abstract, even if that's possible
It's enough to leave a method with no implementation to set it abstract, inside an abstract class
It's the equivalent of declare in TypeScript, and extern in C#, those are used for interoperability with other runtimes, which means you're telling the compiler "Don't worry about this method's implementation, I promise it will exist at runtime", the runtime may be in C or Javascript or whatever
In case, if you are wondering why or where should I even use external keyword, here is a one more example for Flutter.
class MyStruct extends Struct {
#Int32()
external int a;
#Float()
external double b;
external Pointer<Void> c;
}
Sometimes, but not often when you play with native libraries, in this case with Struct to access native struct's field in memory. Under Struct We must declare all fields as external because it will be external fields from dart:ffi (C / C++).
So, external is more than just way to declare "abstract method".
9.4 External Functions
An external function is a function whose
body is provided separately from its
declaration.
What this does mean is that you define the function, but without implementation. It's exactly how you define the abstract method, but the only difference is that with external you don't implement the method in dart but in C or something else.
Something like String class it can be considered as external functions except that the String class it marked with #pragma('vm:entry-point') which make the entire class use native code.
See the following example to understand:
This dart's side.
https://github.com/dart-lang/sdk/blob/main/sdk/lib/core/string.dart#L711
This the implementation in C++.
https://github.com/dart-lang/sdk/blob/main/runtime/lib/string.cc#L467-#L472
In my opinion it is an equivalent of Java native keyword. For example, since current time milliseconds is implemented differently on Android, iOS, Linux etc, DateTime.now().millisecondsSinceEpoch will be linked to different implementations at runtime. So it is not initially known how this method will look like. For this reason it is marked as external meaning it is platform dependent.
Using the ideas outlined in ding the article Using Dart with JSON Web Services at https://www.dartlang.org/articles/json-web-service/, I have been trying to implement the section on using JsonObject and interfaces to produce a strong typing of JSON data.
The article indicates that one should write something like.
abstract class Language {
String language;
List targets;
Map website;
}
class LanguageImpl extends JsonObject implements Language {
LanguageImpl();
factory LanguageImpl.fromJsonString(string) {
return new JsonObject.fromJsonString(string, new LanguageImpl());
}
}
However the compiler 'fail' at the definition of the class LanguageImpl with the message
Missing inherited members: 'Language.website', 'Language.targets' and
'Language.language'
Even more confusing the code will run without a problem....
In Darteditor you get Quick fix support for this.
Set the caret at LanguageImpl and press ctrl+1 or use the context menu > Quick fix.
You get the missing concrete implementations you inherit from the abstract base class generated automatically.
Dart is a dynamic language and therefor very flexible.
The tools support you and try to give meaningful warnings and hints about what could go wrong
but don't prevent you running a program even when it is not yet finished.
You can use the #proxy annotation on the class to silent the warnings.
This also needs the class to have a noSuchMethod() implementation.