10

Here's the ugly long code:

var i;
if(true)
  i = 1;
else
  i = 0;

When I try this:

var i = (true ? 0 : 1);

it doesn't work resulting in an error on the following line. I guess I was a bit inattentive reading Dart's syntax specs, so can anybody show me the right way?

2
  • What's the error you are getting? I just get a 'Dead code' warning. Commented Jan 16, 2014 at 7:58
  • That's not directly an answer and maybe just an error on SO, but the two snippets produce different results. var i = (true ? 1 : 0) would be the equivalent, you switched the "if" and "else" there. Commented Jan 16, 2014 at 9:20

1 Answer 1

12

This looks perfectly fine from a syntax point of view. You can omit the parentheses.

I get a warning 'Dead code' at '1' with your example because of 'true'.
The Darteditor shows you a hint that you wrote code that may contain a bug because he knows your expression can never evaluate to 1 because of the hardcoded 'true'.

void main(List<String> args) {
    var b = true;
    var i = b ? 0 : 1;
}

doesn't produce a warning.

Sign up to request clarification or add additional context in comments.

5 Comments

What about check to null? bool b; var i = b ? 0 : 1; type 'Null' is not a subtype of type 'bool' of 'boolean expression'.
This is a runtime error due to a not initialized variable. That has nothing to do with syntax and IMHO not with the question.
Question is "How to shorten code when I do a variable assignment in a condition in Dart?". Your answer to main question not take that if shorten code in your manner you can get runtime error. var i = (b == null ? false : true) ? 0 : 1;
Good point. @snitko 's example is a bit too simplified due to his true literal.
Ok, thanks. For some reason it just didn't work in my case. I'll check my code again.

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.