What is this constructor name with dot - dart

In flutter's Image widget, I found the use of constructor name with dot (.) like Image.asset() and Image.file().
What is it and how it is used?

It is a named constructor
Use a named constructor to implement multiple constructors for a class
or to provide extra clarity:
class Point {
num x, y;
Point(this.x, this.y);
// Named constructor
Point.origin() {
x = 0;
y = 0;
}
}

Related

Instantiating a subclass in a superclass?

abstract class A {
A(this.x, this.y);
// error: abstract classes cannot be instantiated
//
// another issue: even if you used a base concrete class
// to perform this operation, it would lose type information.
A copy({int? x, int? y}) => A(x ?? this.x, y ?? this.y);
final int x;
final int y;
}
class B extends A {
// Forced to implement copy and similar
// methods on all classes that extend A,
// which is problematic when that number
// is large or changes are necessary.
}
Is there a way to solve this problem or do I have to essentially rewrite the same code for all classes that extend A?
You can, but it requires you to do quite a lot of the work
you are asking to avoid:
class A<T extends A<T>> {
final T Function(int, int) _constructor;
final int x;
final int y;
A._(this._constructor, this.x, this.y);
T copy({int? x, int? y}) => _constructor(x ?? this.x, y ?? this.y);
}
class B extends A<B> {
B(int x, int y) : super._((int x, int y) => B(x, y), x, y);
}
(The code will get shorter when Dart gets constructor tear-offs, then it's just, super._(B, x, y);.)
You cannot, currently, inherit constructors, and you can't create an instance of a type that you don't know yet (because constructors are not inherited, so you don't know if the constructor exists). The only way to abstract over actual behavior (which code to run) is to capture it in a closure and pass it as a function.

In Xtext, how to tweak certain function calls

I am using Xtext 2.15 to generate a language that, among other things, processes asynchronous calls in a way they look synchronous.
For instance, the following code in my language:
int a = 1;
int b = 2;
boolean sleepSuccess = doSleep(2000); // sleep two seconds
int c = 3;
int d = 4;
would generate the following Java code:
int a = 1;
int b = 2;
doSleep(2000, new DoSleepCallback() {
public void onTrigger(boolean rc) {
boolean sleepSuccess = rc;
int c = 3;
int d = 4;
}
});
To achieve it, I defined the grammar this way:
grammar org.qedlang.qed.QED with jbase.Jbase // Jbase inherits Xbase
...
FunctionDeclaration return XExpression:
=>({FunctionDeclaration} type=JvmTypeReference name=ValidID '(')
(params+=FullJvmFormalParameter (',' params+=FullJvmFormalParameter)*)?
')' block=XBlockExpression
;
The FunctionDeclaration rule is used to define asynchronous calls. In my language library, I would have as system call:
boolean doSleep(int millis) {} // async FunctionDeclaration element stub
The underlying Java implementation would be:
public abstract class DoSleepCallback {
public abstract void onTrigger(boolean rc);
}
public void doSleep(int millis, DoSleepCallback callback) {
<perform sleep and call callback.onTrigger(<success>)>
}
So, using the inferrer, type computer and compiler, how to identify calls to FunctionDeclaration elements, add a callback parameter and process the rest of the body in an inner class?
I could, for instance, override appendFeatureCall in the language compiler, would it work? There is still a part I don't know how to do...
override appendFeatureCall(XAbstractFeatureCall call, ITreeAppendable b) {
...
val feature = call.feature
...
if (feature instanceof JvmExecutable) {
b.append('(')
val arguments = call.actualArguments
if (!arguments.isEmpty) {
...
arguments.appendArguments(b, shouldBreakFirstArgument)
// HERE IS THE PART I DON'T KNOW HOW TO DO
<IF feature IS A FunctionDeclaration>
<argument.appendArgument(NEW GENERATED CALLBACK PARAMETER)>
<INSERT REST OF XBlockExpression body INSIDE CALLBACK INSTANCE>
<ENDIF>
}
b.append(');')
}
}
So basically, how to tell if "feature" points to FunctionDeclaration? The rest, I may be able to do it...
Related to another StackOverflow entry, I had the idea of implementing FunctionDeclaration in the inferrer as a class instead of as a method:
def void inferExpressions(JvmDeclaredType it, FunctionDeclaration function) {
// now let's go over the features
for ( f : (function.block as XBlockExpression).expressions ) {
if (f instanceof FunctionDeclaration) {
members += f.toClass(f.fullyQualifiedName) [
inferVariables(f)
superTypes += typeRef(FunctionDeclarationObject)
// let's add a default constructor
members += f.toConstructor [
for (p : f.params)
parameters += p.toParameter(p.name, p.parameterType)
body = f.block
]
inferExpressions(f)
]
}
}
}
The generated class would extend FunctionDeclarationObject, so I thought there was a way to identify FunctionDeclaration as FunctionDeclarationObject subclasses. But then, I would need to extend the XFeatureCall default scoping to include classes in order to making it work...
I fully realize the question is not obvious, sorry...
Thanks,
Martin
EDIT: modified DoSleepCallback declaration from static to abstract (was erroneous)
I don't think you can generate what you need using the jvm model inferrer.
You should provide your own subclass of the XbaseCompiler (or JBaseCompiler, if any... and don't forget to register with guice in your runtime module), and override doInternalToJavaStatement(XExpression expr, ITreeAppendable it, boolean isReferenced) to manage how your FunctionDeclaration should be generated.

Why does F# compiler prefer to generate closed implementations of FSharpFunc types?

For this code:
module Module =
let func x y z = 0
[<EntryPoint>]
let main args =
func 1
func 1 1
0
Decompilation yields:
[CompilationMapping(SourceConstructFlags.Module)]
public static class Main
{
[CompilationMapping(SourceConstructFlags.Module)]
public static class Module
{
[Serializable]
internal sealed class main#30 : OptimizedClosures.FSharpFunc<object, object, int>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[CompilerGenerated]
[DebuggerNonUserCode]
public int x;
[CompilerGenerated]
[DebuggerNonUserCode]
internal main#30(int x)
{
this.x = x;
}
public override int Invoke(object y, object z)
{
return func(x, y, z);
}
}
[Serializable]
internal sealed class main#31-1 : FSharpFunc<object, int>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[CompilerGenerated]
[DebuggerNonUserCode]
public int x;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[CompilerGenerated]
[DebuggerNonUserCode]
public int y;
[CompilerGenerated]
[DebuggerNonUserCode]
internal main#31-1(int x, int y)
{
this.x = x;
this.y = y;
}
public override int Invoke(object z)
{
return func(x, y, z);
}
}
[CompilationArgumentCounts(new int[]
{
1,
1,
1
})]
public static int func<a, b, c>(a x, b y, c z)
{
return 0;
}
[EntryPoint]
public static int main(string[] args)
{
int x = 1;
new main#30(x);
int x2 = 1;
int y = 1;
new main#31-1(x2, y);
return 0;
}
}
public static a Dump<a>(a arg00)
{
return arg00.Dump();
}
}
It generates a concrete type, that is generic parameters are provided at type definition. Why is not this done at the point of construction? I also noticed that types are generated in the module where call occurs, not where func is defined.
Having let func x y z = ... we need implementations of types to cover all possibilities:
FSharpFunc<T1,FSharpFunc<T2,T3,TReturn>>
FSharpFunc<T1,T2,FSharpFunc<T3,TReturn>>
FSharpFunc<T1,FSharpFunc<T2,FsharpFunc<T3,TReturn>>>
Compiler could generate all possible combinations in the same place, where function is defined, closing only for parameters with inferenced types.
You could argue that for the list of 7 args the set of types going to be quite large, but types like FSharpFunc<T1,T2,..,Tn, FSharpFunc<...>> are a mere optimazation. And FSharpFunc supports up to six generic types, then compiler has to switch to FSharpFun<T1,T2,T3,T4,T5,FSharp<...>>.
As pointed out by Fyodor it's not function creation that makes the compiler generating the hidden classes. The hidden classes are used to implement partial application.
In F# a partial application and lambdas are implemented as a compiler generated class that extends an abstract class. C# lambdas rely on delegates instead. IIRC Java and Scala use a similar technique to F# as JVM doesn't have delegates.
I suspect the F# compiler generates a class per partial application because it's simpler than collecting all partial applications and coalesce the identical ones.
It also helps the debuggability of F# programs as the name hints where the partial application was done: main#31-1 => In the main function at row 31. This name if included in logs or performance runs can help identifying what partial application is causing problems.
This comes at the cost of increasing the size of the F# assembly file as noted in a comment by Pavel.

providing default implementation for method in abstract class

In the example below I was hoping sum getter would return 8, but it is a compile error.
Class 'B' has no instance getter 'sum'.
According to the spec:
Using an abstract class instead of an interface has important
advantages. An abstract class can provide default implementations; it
can also provide static methods, obviating the need for service
classes such as Collections or Lists, whose entire purpose is to group
utilities related to a given type.
What is the correct way to provide a default implementation of sum that adds x and y?
abstract class A {
int get x;
int get y;
int get sum => x+y;
}
class B implements A {
int get x => 3;
int get y => 5;
}
main() {
B b = new B();
print(b.x);
print(b.sum); // Not working, why not 8?
}
You have to make B extend A instead of implement.
abstract class A {
int get x;
int get y;
int get sum => x+y;
}
class B extends A {
int get x => 3;
int get y => 5;
}
main() {
B b = new B();
print(b.x);
print(b.sum); // displays 8
}
Alternatively if you don't want to use extends because your class may already extend an other class, you can use mixins :
abstract class M {
int get x;
int get y;
int get sum => x+y;
}
class A {
String s = "s";
}
class B extends A with M {
int get x => 3;
int get y => 5;
}
main() {
B b = new B();
print(b.s);
print(b.x);
print(b.sum); // displays 8
}
Another way around this issue is to just use extensions (depending on your use case). This way all your default method implementations will work regardless if you extend, implement, mixin, ect.
abstract class A {
int get x;
int get y;
}
class B implements A {
int get x => 3;
int get y => 5;
}
extension E on A {
int get sum => x+y;
}
main() {
B b = new B();
print(b.x);
print(b.sum); // 8
}
By choosing to implement A, you have to implement everything A requires even if you have provided default implementations. If you want to use default implementation from A while having the flexibility to provide your own implementations you have to use A as a mixin:
class B with A {
int get x => 3;
int get y => 5;
}

Call global function from within Delphi class's method

Is it possible to call global methods from within a class where they are obscured by member functions of the same name?
I know in C++ you have the following syntax:
int var = 0;
void temp() {
int var = 2;
::var = var;
} //Global var is set to 2
Yes you can by using the name of the unit instead of ::
Like:
unit1.var := 2;
See for more details:
http://delphi.about.com/od/beginners/l/aa060899.htm
You can try
UnitName.VarName := 2

Resources