I like to assign the return value of a function to a variable, but inline. The following is how you would do it not inline.
bool isValid() {
if(a == b) return true;
if(a == c) return true;
return false;
}
bool result = isValid();
What I want is something like
bool result = () {
if(a == b) return true;
if(a == c) return true;
return false;
}
However it displays the error
The argument type 'Null Function()' can't be assigned to the parameter type 'bool'
How do I achieve this?
You are defining a lambda expression. This works the same way as in Javascript, Typescript or many other languages.
bool result = () {
if(a == b) return true;
if(a == c) return true;
return false;
}
This code defines an anonymous function of type () -> bool (accepts no parameters and returns bool). And the actual type of the result variable is bool so the compilation is broken (() -> bool and bool are non-matching types).
To make it correct just call the function to get the result.
bool result = () {
if(a == b) return true;
if(a == c) return true;
return false;
}();
Now you define an anonymous function (lambda) and then call it so the result is bool. Types are matching and there's no error.
This is rather an uncommon behaviour to define the function and immediately call it. It's used in Javascript to create a separate scope for variables using closures (some kind of private variables). I would recommend you to move the code to some kind of class or pass a, b, c parameters directly to the function:
bool isValid(a, b, c) {
/* Your code */
}
It's more generic that way and could be reused. Immediately called lambda is often a sign of bad design.
Related
My current goal is to remove this code duplication:
final int? myNullableInt = 10;
/// Everywhere I need to do this null verification:
if (myNullableInt == null) return null;
return someOtherMethodThatReceivesANonNullableInt(myNullableInt);
I want to convert to something like we have in Kotlin:
final int? myNullableInt = 10;
return myNullableInt?.apply((myInt) => someOtherMethodThatReceivesANonNullableInt(myInt));
I did it:
extension ApplyIfNotNull on Object? {
T? apply<T extends Object?>(Object? obj, T? Function(Object) fn) {
if (obj == null) return null;
return fn(obj);
}
}
But this gives me a static error:
The argument type 'Object' can't be assigned to the parameter type 'int'.
Note: this should work with all types, e.g ints, Strings, double and MyOwnClassTypes.
Is there something I can do? or am I missing something?
extension ApplyIfNotNull on Object? {
T? apply<T extends Object?>(Object? obj, T? Function(Object) fn) {
if (obj == null) return null;
return fn(obj);
}
}
That doesn't work because it declares that the callback be capable of accepting any Object argument, but you're presumably trying to use it with a function that accepts only an int argument. It's also unclear why you've made an extension method since it doesn't involve the receiver (this) at all.
You need to make your function generic on the callback's argument type as well:
R? applyIfNotNull<R, T>(T? obj, R Function(T) f) =>
(obj == null) ? null : f(obj);
(That's the same as what I suggested in https://github.com/dart-lang/language/issues/360#issuecomment-502423488 but with the arguments reversed.)
Or, as an extension method, so that it can work on this instead of having the extra obj argument:
extension ApplyIfNotNull<T> on T? {
R? apply<R>(R Function(T) f) {
// Local variable to allow automatic type promotion. Also see:
// <https://github.com/dart-lang/language/issues/1397>
var self = this;
return (self == null) ? null : f(self);
}
}
Also see https://github.com/dart-lang/language/issues/360 for the existing language feature request and for some other suggested workarounds in the meantime.
Let's say I have:
class Test<T> {
void method() {
if (T is int) {
// T is int
}
if (T == int) {
// T is int
}
}
}
I know I can override == operator but what's the main difference between == and is in Dart if I don't override any operator.
Edit:
Say I have
extension MyIterable<T extends num> on Iterable<T> {
T sum() {
T total = T is int ? 0 : 0.0; // setting `T == int` works
for (T item in this) {
total += item;
}
return total;
}
}
And when I use my extension method with something like:
var addition = MyIterable([1, 2, 3]).sum();
I get this error:
type 'double' is not a subtype of type 'int'
identical(x, y) checks if x is the same object as y.
x == y checks whether x should be considered equal to y. The default implementation for operator == is the same as identical(), but operator == can be overridden to do deep equality checks (or in theory could be pathological and be implemented to do anything).
x is T checks whether x has type T. x is an object instance.
class MyClass {
MyClass(this.x);
int x;
#override
bool operator==(dynamic other) {
return runtimeType == other.runtimeType && x == other.x;
}
#override
int get hashCode => x.hashCode;
}
void main() {
var c1 = MyClass(42);
var c2 = MyClass(42);
var sameC = c1;
print(identical(c1, c2)); // Prints: false
print(identical(c1, sameC)); // Prints: true
print(c1 == c2); // Prints: true
print(c1 == sameC); // Prints: true
print(c1 is MyClass); // Prints: true
print(c1 is c1); // Illegal. The right-hand-side must be a type.
print(MyClass is MyClass); // Prints: false
}
Note the last case: MyClass is MyClass is false because the left-hand-side is a type, not an instance of MyClass. (MyClass is Type would be true, however.)
In your code, T is int is incorrect because both sides are types. You do want T == int in that case. Note that T == int would check for an exact type and would not be true if one is a derived type of the other (e.g. int == num would be false).
Basically, == is equality operator and "is" is the instanceof operator of Dart (If you come from Java background, if not, it basically tells you if something is of type something).
Use == for equality, when you want to check if two objects are equal. You can implement the == operator (method) in your class to define on what basis do you want to judge if two objects are equal.
Take this example:
class Car {
String model;
String brand;
Car(this.model, this.brand);
bool operator == (otherObj) {
return (otherObj is Car && other.brand == brand); //or however you want to check
//On the above line, we use "is" to check if otherObj is of type Car
}
}
Now you can check if two cars are "equal" based on the condition that you have defined.
void main() {
final Car micra = Car("Micra", "Nissan");
print(micra == Car("Micra", "Nissan")); // true
print(micra is Car("Micra", "Nissan")); // true
}
Hence, == is something you use to decide if two objects are equal, you can override and set it as per your expectations on how two objects should be considered equal.
On the other hand, "is" basically tells you if an instance is of type object (micra is of type Car here).
How do I check if a value is a number (even or odd) with type double in Dart?
double value = 2.5;
print(value.floor().isEven ? "It's even" : "It's odd");
You can go traditional with String evenOrOdd = number %2 == 0?'even':'odd'
There are native methods for int to achieve that purposes. You can convert the number to an int and call number.isOdd, number.isEven...
Documentation:
abstract class int extends num {
/// Returns true if and only if this integer is odd.
bool get isOdd;
// Returns true if and only if this integer is even.
bool get isEven;
}
Here is the code to detect from String.
bool isDouble(String? s) {
if (s == null) {
return false;
}
if(int.tryParse(s)!=null){
return false;
}
return double.tryParse(s)!= null;
}
Is there a working way to check if a double variable is NaN?
I tried:
variable.isNaN
variable == double.nan
Here the complete code:
bool isValidQuantity(String s) {
double converted = toDouble(s);
if (converted == double.nan || converted < 0) {
return false;
}
return true;
}
toDouble() is a function of the library validators version 2.0.0+1
It just returns double.nan in this case so I don't get why false isn't returned by the isValidQuantity() function
It is working fine. However, you might want to initialize your variable because in dart everything is Object(any int, float, bool etc) and default values of the object are Null.
var myVar = 0.0;
if (myVar.isNaN)
print('Not a number');
else
print('${myVar} is a number');
what is the return type of this sort of bool function...... i know the return type is either true of false but this seems complicated when you have got like this..
bool mypredicate (int i, int j) {
return (i==j);
}
this bool function are used in a library function called equal...... another example is....
bool compare(int a, int b){
return a<b;
}
so what are the perspective here to return type of these bool function.when is goes true & false....
Your functions mypredicate and compare are merely thin wrappers over the binary operators == and <. Operators are like functions: they take a number of arguments of a given type, and return a result of a given type.
For example, imagine a function bool operator==(int a, int b) with the following specification:
if a equals b then return true
otherwise return false
And a function bool operator<(int a, int b) with the following specification:
if a is strictly lesser than b then return true
otherwise return false.
Then you could write:
bool mypredicate (int i, int j) {
return operator==(i, j);
}
bool compare(int a, int b){
return operator<(a, b);
}
For convenience, most programming languages allow you to use a shorter, functionnaly equivalent syntax: i == j and a < b.