educative.io

Educative

Much ado about nulling

When I run the code

import ‘dart:io’;

main() {
print("Hello " + stdin.readLineSync());
}

in my terminal. I receive an error message:


dart.dart:4:26: Error: A value of type ‘String?’ can’t be assigned to a variable of type ‘String’ because ‘String?’ is nullable and ‘String’ isn’t.
print("Hello " + stdin.readLineSync());

I was able to get the program to run with it’s original intended purpose with the following code:


import ‘dart:io’;

main() {
print(“Type in anything you’d like for me to say hello to:”);
// My attempt to assign ‘stdin’ to a variable other than string
var string = stdin.readLineSync();
// Implementing the new variable in place of the original string
print(“Hello $string”);
}

Hooray! I did it. But, I don’t know what I did, why it worked, and most important, why the code from class didn’t.

Please help me in understanding what is or is not happening. Thank you.

Hi @sean2

I have executed both of the codes on the online compiler because I am not sure which course and lesson you are referring to, and both of the codes are running perfectly fine without any errors.

Can you please share the lesson link? So, that I can check it out in the lesson as well. And please feel free to get back to us if you have any query.

Thanks.