7

How to declare a variable depending on if statement in Dart? In Kotlin it would look like this:

   val max = if (a > b) {
        a
    } else {
        b
    }

Is it even possible in Dart?

1

2 Answers 2

8

@pskink's answer in the comment is correct but it didn't show how you would be able to do it in this scenario. Here is how you can do it in your scenario:

final max= a > b ? a : b;

The final keyword in Dart is the same as the val keyword in Kotlin. You will not be able to change the value of the variable. You could also use the var keyword in Dart which is the same as Kotlin's var keyword. You will be able to change the value of the variable after declaring it. You might be confused with the one-liner code since there isn't any if or else statements inside it. The code above is called a ternary operator.
Here is an explanation for it:

(condition/expresssion) ? val1(if true execute this) : val2(if false execute this)
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to execute more than one statement?
what do you mean with that @AnimeshSahu
@AnimeshSahu that's not possible with ternary operators. You would have to use if and else statements to do it :( You could do if(){max=a}else{max=b} to execute more than one statement.
Ternary operator is perfect if you have only 2 statements. But I didn't find a way to assign variable without boilerplate when we have 3+ statements. Like here: val c = if (a > b) { a } else if (a == b) { 0 } else { b }
5

For more than one statement, we can use a method by declaring its type as int.

void main() {
    print(declareVariable());
}

int a = 10;
int b = 30;          

int declareVariable() {
 if(b < a){
   return 1;
 }
 else if(b > a) {
   return 2;
 } 
  else {
    return 0;
  }
} 

Edited :

We can declare more then one condition in single line in the same way.

var singleLine = b < a ? 1 : b > a ? 2 : 0;

This will print out the same answer as method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.