Problem concerning null safety in functions - flutter

I have this function called add which adds two numbers and returns the result in dart.
void main() {
int step1Result = add(n1: 5, n2: 9);
int step2Result = multiply(step1Result, 5);
double finalResult = step2Result / 3;
print(finalResult);
}
int add({int n1, int n2}){
return n1 + n2;
}
but it keeps on throwing the error that n1 and n2 can't have a value of 'null' because of its type, but the implicit default value is 'null'.
I tried adding the ? mark but the it threw another error saying
The operator '+' can't be unconditionally invoked because the receiver can be 'null'.

The error comes from the declaration of your add function:
Here
int add({int n1, int n2}){
// ...
}
Here you're declaring two optional parameters to the functions.
But n1 and n2 are int and not int?
To fix this issue, you can either transform your function to take int? types.
Or to add the required keyword to tell that the function will only work if both parameters will be given.
void main() {
int step1Result = add(n1: 5, n2: 9);
int step2Result = multiply(step1Result, 5);
double finalResult = step2Result / 3;
print(finalResult);
}
int add({required int n1,required int n2}){
return n1 + n2;
}
You can learn more about null-safety syntax and principles on the official documentation: https://flutter.dev/docs/null-safety.
https://api.flutter.dev/flutter/material/DropdownButton-class.html.

Related

How do I inject an anonymous function directly into an enum

For Dart 2.17, we can use constructors in enum similarly to how we do with classes.
I am trying to insert an anonymous function inside of an enum directly.
here is code that works but doesn't do exactly what I'd like it to do.
int _add(int a, int b) => a + b;
int _sub(int a, int b) => a - b;
int _mul(int a, int b) => a * b;
double _div(int a, int b) => a / b;
enum MyEnum {
addition(_add),
subtract(_sub),
multiplication(_mul),
division(_div);
final Function fx;
const MyEnum(this.fx);
}
void main() {
var fun = MyEnum.addition;
print(fun.fx(1, 2));
fun = MyEnum.subtract;
print(fun.fx(1, 2));
fun = MyEnum.multiplication;
print(fun.fx(1, 2));
fun = MyEnum.division;
print(fun.fx(1, 2));
}
Instead of making a function somewhere else in the code, as the _add, _sub, _mul, _div, I would like to directly insert an anonymous function into the enum, like in the following code (please note that the following code does not work).
What I'd like to do
enum MyEnum {
// I'd like to insert an anonymous function instead.
addition((int a, int b) => _add(a, b)),
subtract((int a, int b) => a - b),
multiplication(int a, int b) => a * b),
division((int a, int b) => a / b;);
final Function fx;
const MyEnum(this.fx);
}
Is it possible? Would anyone be able to show me how to do this? I cannot figure out what I am doing wrong.
One point of Dart 2.17 is that you no longer need to use extensions. The following code, which incorporates the features of Dart 2.17, is how I solved it. Though this certainly is not as elegant nor satisfying as I would have hoped it would have been in my original post.
enum MyEnum {
addition(),
subtract(),
multiplication(),
division();
Function fx() {
switch (this) {
case addition:
return (int a, int b) => a + b;
case subtract:
return (int a, int b) => a - b;
case multiplication:
return (int a, int b) => a * b;
case division:
return (int a, int b) => a / b;
default:
throw Exception('Unknown operation');
}
}
const MyEnum();
}
void main() {
var fun = MyEnum.addition;
print(fun.fx()(1, 2));
fun = MyEnum.subtract;
print(fun.fx()(1, 2));
fun = MyEnum.multiplication;
print(fun.fx()(1, 2));
fun = MyEnum.division;
print(fun.fx()(1, 2));
}
Have you tried extensions? I'm not sure you'll be able to do everything you want (as happened to me), but they almost got the job done. Sometimes I just have to invoke the extension instead of the enum, probably when I put some static method on the extension (like calling SexExt.staticMethod() instead of Sex.staticMethod), but I find them pretty useful.
enum Sex { MALE, FEMALE }
extension SexExt on Sex {
String getText() {
switch (this) {
case Sex.MALE:
return "Maschio";
case Sex.FEMALE:
return "Femmina";
}
}
String getShortText() {
switch (this) {
case Sex.MALE:
return "M";
case Sex.FEMALE:
return "F";
}
}
}

Why does the identity function break type inference of function composition in Dart?

I have a function that composes 3 functions while preserving type inference. Notice that my composition function is left-associative, so the functions are applied left to right.
D Function(A) compose3<A, B, C, D>(
B Function(A) fa, C Function(B) fb, D Function(C) fc) =>
(x) => fc(fb(fa(x)));
int incr(int x) => x + 1;
T id<T>(T x) => x;
The following code works as expected. The type of res is correctly inferred to be int.
void main() {
var res = compose3(incr, incr, incr)(7);
print('$res, ${res.runtimeType}'); // 10, int
}
However, after inserting the id function in the middle, the code does not compile.
var res = compose3(incr, id, incr)(7); // error
There are two errors:
Couldn't infer type parameter 'C'.
Tried to infer 'dynamic' for 'C' which doesn't work:
Parameter 'fc' declared as 'D Function(C)'
but argument is 'int Function(int)'.
The type 'dynamic' was inferred from:
Parameter 'fb' declared as 'C Function(B)'
but argument is 'dynamic Function(dynamic)'.
Consider passing explicit type argument(s) to the generic.
and
The argument type 'int Function(int)' can't be assigned to the parameter type 'int Function(dynamic)'.
I have tried explicitly specifying the return type, but it didn't help.
int res = compose3(incr, id, incr)(7); // error
The following makes the errors go away, but it defeats the purpose of the id function.
T id<T extends int>(T x) => x;
Also, explicitly applying the functions works.
void main() {
var res = incr(id(incr(7)));
print('$res, ${res.runtimeType}'); // 9, int
}
This has been tested in Dartpad with null safety, Dart SDK 2.14.3.
Why does the id function break type inference in function composition and how can I make it work as expected?
Here's a solution using an extension method.
extension ComposeExtension on Function {
C Function(A) pipe<A, B, C>(C Function(B) f) => (x) => f(this(x));
}
int incr(int x) => x + 1;
T id<T>(T x) => x;
void main() {
var res = incr
.pipe(id)
.pipe(incr)(7);
print('$res, ${res.runtimeType}'); // 9, int
}

nested primary expressions in swift

I'm wondering how to handle this expression with swift. I implimented it in ruby like this:
def disperseValueIntoNSpaces(n,m)
accum = 0
dispersedValue = []
for k in 0...m
valCrt = ((n*(m-k))/m+0.5)-((n*(m-k-1))/m+0.5)
dispersedValue.push(valCrt.to_i)
accum += valCrt
end
return dispersedValue
end
and transferred it to swift like this:
func disperseValueIntoNSpaces(numOfRows: Int, spaces: Int) -> [Int] {
var accum: Int = 0
var n: Float = Float(numOfRows)
var m: Float = Float(spaces)
var dispersedValues: [Int] = []
for k in (0...spaces) {
let valCrt = ((n*(m-k))/m)+0.5) - ((n*(m-k-1))/m+0.5)
// error: expected expression
// error: Binary operator '-' cannot be applied to operands of type 'Float' and 'Int'
// error: Consecutive statements on a line must be separated by ';'
dispersedValues.append(Int(valCrt))
accum += valCrt
}
return dispersedValues
}
This Float minus an Int error is easy enough to fix but i'm not sure how to craft the math equation

Swift 2.1 Closure

At first, I apologize for my English!
Please help me detect when I was wrong.
let arrayInt = [0, 1, 2, 3, 4, 5, 7, 8, 9]
func myF(array: [Int], cl:(n1: Int, n2: Int) -> Bool) -> Int {
var number : Int
for value in array {
if cl(n1: number, n2: value) {
number = value
}
}
return number
}
myF(arrayInt, { cl: (n1: Int, n2: Int) -> Bool in
return n1 < n2
})
The function takes an array of Int and closure returns Int. Closure should take two Int numbers and return Bool yes or no. It is necessary to walk in a loop through the array and compare elements of array with variable using closure . If closure returns yes, you write the value of the array into variable. At the end of the function returns the variable. We need find max and min value in array.
I have 3 issue:
consecutive statements on a line must be separated by ';'
expected expression
contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored
Please don't proposed me use method "sort()". I am learning of "closure".
First of all you need to initialize your number variable: var number : Int -> var number = 0
Second, the function call with closure is not correct. There are several ways to call a closure:
let y = myF(arrayInt, cl: { (n1: Int, n2: Int) -> Bool in
return n1 < n2
})
or
let x = myF(arrayInt) { (n1, n2) -> Bool in
return n1 < n2
}
or even
let z = myF(arrayInt) { n1, n2 in
return n1 < n2
}
and
let w = myF(arrayInt) { $0 < $1 }
This link and this one should help you
Full code sample:
let arrayInt = [1, 2, 3, 0, 4]
func myF(array: [Int], cl: (n1: Int, n2: Int) -> Bool) -> Int {
var number = 0
for i in array {
if cl(n1: number, n2: i) {
number = i
}
}
return number
}
let x = myF(arrayInt) { (n1, n2) -> Bool in
return n1 < n2
}
First replace:
myF(arrayInt, { cl: (n1: Int, n2: Int) -> Bool in
by:
myF(arrayInt, cl: { (n1: Int, n2: Int) -> Bool in
because cl is the parameter name and all included in { } is the closure.
Second initialize number in myF function replacing:
var number : Int
by:
var number = array[0]
if the goal of the closure is to find max or min value.

Can I define implicit cast behaviour for a class in Haxe?

Is it possible to define implicit casts for classes?
For instance, I have a class Color:
class Color {
public var r: Int;
public var g: Int;
public var b: Int;
public function new(?r: Int = 0, ?g: Int = 0, ?b: Int = 0) {
this.r = r;
this.g = g;
this.b = b;
}
}
If I have a Array<Int> like this:
var myIntegerArray = [255, 0, 255]; // color written in RGB as an array
var c: Color = myIntegerArray; // <= how to make this possible?
trace(c.r);
I tried #:from on a static function in my class:
#:from
static public function fromArray(a: Array<Int>) {
return new Color(a[0], a[1], a[2]);
}
but the compiler is still not happy about this (Error: Array<Int> should be Color).
I know I could just use the static function like var c = Color.fromArray(myIntegerArray); but I'm curious whether or not it is possible to implicitly cast it.
No, implicit cast for normal class is impossible. But you have three solutions:
Create abstract Color(Array<Int>) instead class;
Use "chain" e.g. class Color > abstract ColorAbs > Array<Int>;
Use haxe.extern.EitherType<Color, Array<Int>>;
I don't recommend the second solution.