import 'package:equatable/equatable.dart';
class Point extends Equatable {
const Point(this.x, this.y);
final int x;
final int y;
#override
List<Object?> get props => [x, y];
#override
bool? get stringify => true;
Point operator +(Point other) {
return Point(x + other.x, y + other.y);
}
Point operator *(int other) {
return Point(x * other, y * other);
}
}
void main() {
print(Point(1, 1) == Point(1, 1));
print(Point(2, 1));
}
What does "Stringify" and "get props" does is this block of code?
It is given that "If set to true, the [toString] method will be overridden to output this instance's [props]." regarding the use of Stringify. What does it mean by "this instance's [props]."?
The purpose of the equatable package are described as:
A Dart package that helps to implement value based equality without needing to explicitly override == and hashCode.
To do achieve this goal, we can make our classes extend from Equatable (or use the EquatableMixin with with) which will then come with the implementation for == and hashCode.
But Equatable can't inspect the object at runtime to figure out what fields your class have defined. And Equatable does also not require a precompile step. Also, you might not want to compare all fields of your objects when determine that two objects are equal.
So the way Equatable understands what fields you want to have compared, is by using a props getter that you must define if using Equatable. This getter must then return a list of objects that should be compared when determining the equality of two objects.
Behind the scene, Equatable will call this probs getter whenever something calls == or hashCode on your object.
The purpose of the stringify getter is then to tell Equatable if it, besides == and hashCode, should also implement a toString() for your class. By default, the toString() method, in Dart, will just tell you the type of object you have like Instance of 'Point'.
If stringify returns true, then Equatable will use the returned value from probs to contruct its own toString() method which lists the value of each element in probs (which correspond to each field of your class).
It is just an extra optional service if you already want your toString() to list the value of each field of your class.
Related
In Kotlin I can do something like:
var myType : KClass<String>? = null
and can assign to it like:
myType = String::class
but NOT like:
myType = Int::class // Type mismatch: inferred type in KClass<Int> but KClass<String>? was expected
Is there something similar in Dart? I know of the Type type but it is not generic and while it can represent String or List<int> I seem not to be able to write similar code as my Kotlin example:
Type? t = null;
I can assign to it:
t = String;
AND also:
t = int;
but I want the second example to fail compilation. I would need some kind of Type<String>. Is this possible in Dart?
The Type class is not generic, and doesn't support subtype checks (or any other reasonable type-related operation). There is no way to use it for what you are trying to do.
So, don't. It's useless anyway. However, in Dart you can create your own type representation that is actually useful, because Dart doesn't erase type arguments, and you can then ask people using your code to ass that instead.
Say:
class MyType<T> implements Comparable<MyType>{ // Or a better name.
const MyType();
Type get type => T;
bool operator >=(MyType other) => other is MyType<T>;
bool operator <=(MyType other) => other >= this;
bool isInstance(Object? object) => object is T;
R runWith<R>(R Function<T>() action) => action<T>();
#override
int get hashCode => T.hashCode;
#override
bool operator==(Object other) => other is MyType && T == other.type;
}
With that you can write:
MyType<String?> type;
type = MyType<Null>(); // valid
type = MyType<String>(); // valid
type = MyType<Never>(); // valid
type = MyType<int>; // EEEK! compile-time error
You can use it where you need to store a type as a value.
The thing is, most of the time you can just use a type variable instead ,and creating an actual value to represent a type is overkill.
So, first try to just use a type parameter, instead of passing around Type or MyType objects. Only if that fails should you consider using MyType. Using Type is probably a mistake since it's not good for anything except doing == checks, which is antithetical to object orientation's idea of subtype subsumption.
I think this is the best you can get :
void main() {
aFunction<String>(String, '');
aFunction<String>(String, 1);
}
void aFunction<V>(Type type, V value) {
print(value.toString());
}
if you run this in a dartpad, you will see that
aFunction<String>(type, 1);
Doesn't compile.
But that's not really efficient because the type isn't guessed by Dart, you have to specify the generic type by hand.
I'm using Dart 2.17
In a c# dll I have a method, that takes func parameters:
public static AttrDiffRule Create<T>(string a_attr, string b_attr, Func<IAttrProxy,IAttrProxy,T,bool> parametricRule, T ruleParam, string desc = null)
and some predefined default methods intended for it:
public static bool NumberEqualsWithTolerance(IAttrProxy a, IAttrProxy b, double tolerance)
Now when using this in C#, I can write the following and it works:
var tmp = DefaultRules.Create("fds", "fds", DefaultRules.NumberEqualsWithTolerance, 10.0);
But, in F# this:
let attrRule = DefaultRules.Create("fd","fdsa", DefaultRules.NumberEqualsWithTolerance, 89.)
gives syntax error: "Error FS0002 This function takes too many arguments, or is used in a context where a function is not expected"
What would be the correct way to pass a C# static method into a parameter expecting a Func<> in F#?
It is important to actually pass in the function, and not a lambda wrapper, because the Create method's job is to use the argument function's MethodInfo, which gets hidden by the lambda wrapper's one.
The passed in function does not have overloads, also tried with specifying the type in place like
(DefaultRules.NumberEqualsWithTolerance : Func<IAttrProxy,IAttrProxy,float,bool>)
This is a case of F# being very thoughtful on your behalf - by helping you write more idiomatic F#.
In .NET, you are not actually passing in the function, as if it's a member reference, rather you are passing in a delegate object of type Func<>. The construction of the delegate object is done implicitly by C# when it has the necessary type information.
We can see this more clearly if we refactor this into an actual delegate type:
public delegate bool ParametricRule<T>(IAttrProxy a, IAttrProxy b, T value);
public static AttrDiffRule Create<T>(string a_attr, string b_attr, ParametricRule<T> parametricRule, T ruleParam, string desc = null)
{
return default;
}
If you try to construct a ParametricRule in F#, you'll see that its type is:
ParametricRule(IAttrProxy -> IAttrProxy -> 'a -> bool)
The rationale is that this way you can use regular F# functions, instead of some un-F#ish tupled input function. And this why it doesn't work in your case.
Because you're trying to throw the tupled version from C# right back at it.
So if you refactor your C# implementation to:
protected static bool NumberEqualsWithToleranceImpl(IAttrProxy a, IAttrProxy b, float tolerance)
{
return default;
}
public static ParametricRule<float> NumberEqualsWithTolerance => NumberEqualsWithToleranceImpl;
you'll see that it works like you'd expect it to, both from F# and C#.
let attrRule = DefaultRules.Create("fd","fdsa", DefaultRules.NumberEqualsWithTolerance, 89.0f) //compiles, yay!
Sometimes the type resolution has trouble when passing a method as a function parameter, because there can be overloads on the method that make the signature ambiguous. You can just wrap the function in a lambda that passes the parameters.
let attrRule =
DefaultRules.Create(
"fd",
"fdsa",
(fun a b tolerance -> DefaultRules.NumberEqualsWithTolerance(a, b, tolerance)),
89.0)
class X extends Y {
X(int a, int b) : super(a,b);
}
Can someone give me an explanation about the syntax meaning of the colon :?
This feature in Dart is called "initializer list".
It allows you to initialize fields of your class, make assertions and call the super constructor.
This means that it is not the same as the constructor body. As I said, you can only initialize variables and only access static members. You cannot call any (non-static) methods.
The benefit is that you can also initialize final variables, which you cannot do in the constructor body. You also have access to all parameters that are passed to the constructor, which you do not have when initializing the parameters directly in the parentheses.
Additionally, you can use class fields on the left-hand of an assignment with the same name as a parameter on the right-hand side that refers to a parameter. Dart will automatically use the class field on the left-hand side.
Here is an example:
class X {
final int number;
X(number) : number = number ?? 0;
}
The code above assigns the parameter named number to the final field this.number if it is non-null and otherwise it assigns 0. This means that the left-hand number of the assignment actually refers to this.number. Now, you can even make an assertion that will never fail (and is redundant because of that, but I want to explain how everything works together):
class X {
final int number;
X(number): number = number ?? 0, assert(number != null);
}
Learn more.
It's ok to access non static member in initializer list.
class Point {
num x, y;
Point(this.x, this.y);
Point.origin(): this.x = 10, this.y = 10;
}
main() {
Point p = Point.origin();
print(p.x); // 10
}
I need clarity on how objects are declared and assigned a definition in F#.
What's happening in this code?
let service = {
new IService with
member this.Translate(_) = raise error }
My guess is we're creating an object that will implement some interface on the fly even though there is no actual class that's backing this object. Hence, we're removing the ceremony involved with creating an object by not having to declare a separate class to use it. In this case, we're minimizing the ceremony involved for implementing a mock object that could be used within a unit test.
Is my understanding accurate?
I tried to research my question and found the specification for F# 3.0 (Section - 6.3.8 Object Expressions)
6.3.8 Object Expressions An expression of the following form is an object expression: { new ty0 args-expropt object-members interface
ty1 object-members1 … interface tyn object-membersn } In the case
of the interface declarations, the object-members are optional and are
considered empty if absent. Each set of object-members has the form:
with member-defns endopt Lexical filtering inserts simulated $end
tokens when lightweight syntax is used. Each member of an object
expression members can use the keyword member, override, or default.
The keyword member can be used even when overriding a member or
implementing an interface.
For example:
let obj1 =
{ new System.Collections.Generic.IComparer<int> with
member x.Compare(a,b) = compare (a % 7) (b % 7) }
You can get a pretty good picture of what is happening behind the scenes if you look at the generated IL using a decompiler like ILSpy. For the example involving IComparer, it generates a hidden class, which implements the interface:
internal sealed class obj1#2 : IComparer<int> {
public obj1#2() : this() { }
int IComparer<int>.System-Collections-Generic-IComparer(int x, int y) {
int num = x % 7;
int num2 = y % 7;
if (num < num2) { return -1; }
return (num > num2) ? 1 : 0;
}
}
Inside the body of the method, it then creates a new instance:
IComparer<int> obj1 = new obj1#2();
Consider the following piece of code:
class Person {
String id;
String name;
ConnectionFactory connectionFactory;
// What is this constructor doing?
Person({this.connectionFactory: _newDBConnection});
}
If you precede a constructor's argument with this, the corresponding field will be automatically initialized, but why {...}?
This makes the argument a named optional argument.
When you instantiate a Person you can
Person p;
p = new Person(); // default is _newDbConnection
p = new Person(connectionFactory: aConnectionFactoryInstance);
without {} the argument would be mandatory
with [] the argument would be an optional positional argument
// Constructor with positional optional argument
Person([this.connectionFactory = _newDBconnection]);
...
Person p;
p = new Person(); // same as above
p = new Person(aConnectionFactoryInstance); // you don't specify the parameter name
Named optional parameters are very convenient for boolean arguments (but of course for other cases too).
p = new Person(isAlive: true, isAdult: false, hasCar: false);
There is a specific order in which these argument types can be used:
mandatory (positional) arguments (only positional arguments can be mandatory)
optional positional arguments
(optional) named arguments (named arguments are always optional)
Note that positional and named optional arguments use a different delimiter for the default value.
The named requires : but the positional requires =. The language designers argue that the colon fits better with the Map literal syntax (I would at least have used the same delimiter for both).
= is supported as delimiter since Dart 2 and preferred according to the style guide while : is still supporzed.
See also:
What is the difference between named and optional parameters in Dart?
Functions Are Fun, Pt 1 - Dart Tips, Ep 6
Chapter 2. A Tour of the Dart Language - Functions
Chapter 2. A Tour of the Dart Language - Constructors
Dart functions allow positional parameters, named parameters, and optional positional and named parameters, or a combination of all of them.
Positional parameters are simply without decoration:
void debugger(String message, int lineNum) {
// ...
}
Named parameters means that when you call a function, you attach the argument to a label. This example calls a function with two named parameters:
debugger(message: 'A bug!', lineNum: 44);
Named parameters are written a bit differently. You wrap any named parameters in curly braces ({ }). This line defines a function with named parameters:
void debugger({String message, int lineNum}) {
Named parameters, by default, are optional. But you can annotate them and make them required:
Widget build({#required Widget child}) {
//...
}
Finally, you can pass positional parameters that are optional, using [ ]:
int addSomeNums(int x, int y, [int z]) {
int sum = x + y;
if (z != null) {
sum += z;
}
return sum;
}
You call that function like this:
addSomeNums(5, 4)
addSomeNums(5, 4, 3)
You can define default values for parameters with the = operator in the function signature, and the function can be simplified as below:
addSomeNums(int x, int y, [int z = 5]) => x + y + z;
the this. connectionFactory in
Person({this.connectionFactory: _newDBConnection});
is called Automatic Class Member Variable Initialization. See this example