This question already has answers here:
"The argument type 'String?' can't be assigned to the parameter type 'String'" when using stdin.readLineSync()
(3 answers)
Closed 6 months ago.
I am trying to parse an input with the type 'String?' into a double, but it is saying that -
The argument type 'String?' can't be assigned to the parameter type 'String'.
stdout.write("Enter the first number - ");
String? vari = stdin.readLineSync();
var first = int.parse(vari);
Change it to:
int? first = int.tryParse(vari.toString());
This is because String? is nullable, vs String.
.parse functions require non-nullable Strings.
tryParse returns an int if the string is parsable, and returns null if it can't be parsed. This is why I changed var first to int? first.
You can check afterwards if first is null or not. You can also perform this check before parsing it, and your code would look like this:
String? vari = stdin.readLineSync();
if (vari != null) var first = int.parse(vari);
This would work.
Related
A value of type 'String?' can't be assigned to a variable of type 'String'.
Try changing the type of the variable, or casting the right-hand type to 'String'.
This error message i got when i run this code.
This is a simple user input code on dart.
var person = ['abc', 'qwe', 'dfg'];
stdout.write('Enter Index : ');
String p = stdin.readLineSync(); //Error
int per = int.parse(p);
per > person.length
? stderr.write('Index does not exist')
: stdout.write('Person ${person[per]}');
}
Seems like readLineSync() returns nullable type. But you declare variable p as non-nullable. Either declare p as nullable: String? instead of String or make readLineSync() return default value if null:
String p = stdin.readLineSync() ?? "";// will return empty String if method readLineSync() returns null.
First of all check the null safety documentation, you'll learn everything you need to know
https://dart.dev/null-safety/understanding-null-safety
readLineSync returns a value of Type String? Meaning the return value must be a nullable String.
p is of type String and therefore expects a String (not a nullable String). the trick here is to cast stdin.readLineSync() to String:
String p = stdin.readLineSync() as String;
String p = stdin.readLineSync()!; #shorthand syntax
On top of that, your code needs some improvements. What if p can't be cast into an integer? One way to handle this is to add a try block and catch any FormatException.
in Swift or Kotlin I can do something like this
var fullName = myMap["fullName"] as? String
then as a result that fullName data type will be optional String ( String? ).
I need to get optional type after type checking like that
I can't directly perform null coalescing operator to that map, because dart will give weird result. for example like this
// 'data' is Map<String, dynamic>
final fullName = data["fullname"] ?? "John Doe";
final double myNumber = fullName;
as you can see, the IDE will not show an error at all, I expect that fullName will be a String, so it will have an error when I assign a String to myNumber that require double.
If you know in advance that data["fullname"] is a String, then you could do:
final fullName = (data["fullname"] ?? "John Doe") as String;
If data["fullname"] turns out not to be a String at runtime, you'll get a runtime exception from the cast failure. If that's something you need to handle, then you could easily make a trivial helper function that checks if a dynamic value is the desired type first and that returns null if it isn't:
T? tryCast<T>(dynamic object) => object is T ? object : null;
final fullName = tryCast<String>(data["fullname"]) ?? "John Doe";
and now fullName is statically known to be a String, and accidentally assigning it to a double will be a compile-time error.
The safe nullable cast operator known from Kotlin currently doesn't exist in Dart but it soon might.
In your case though, why not simply write
String? fullname = myMap["fullname"];
The nullable cast operator as? in Kotlin yields null if myMap["fullname"] contains anything but a non-null String. As long as you're only dealing with Strings or null, the above works just fine. (And if there's anything but a String or null it crashes, which is probably better than just continue on with null in most situations)
This question already has answers here:
Downcasting in Swift with as and as?
(3 answers)
Closed 8 years ago.
Is there a difference between as? String vs. as String? in Swift? If so, what's the difference and when should I use one vs. another?
There's a subtle but important difference:
variable as? String: variable can be any type, such as an array, an integer, etc. Cast to string if it's a string, set to nil otherwise.
variable as String?: variable is a String?, but stored in an opaque type, such as AnyObject?, or it's a non optional string. If it's something different, a runtime exception is generated.
Some examples:
var x: AnyObject? = "Test"
x as String? // OK, the result is an optional string
x as? String // OK, evaluates to an optional string
"string" as String? // OK, evaluates to optional string
x as? Int // OK, evaluates to nil, it's not an Int
x as Int? // Runtime exception, it's not castable to optional Int
So:
as? Type means: cast to this type, if possible, otherwise evaluate to nil
as Type? means: cast to an optional Type, because I know it's an optional Type. I understand that if it's not that, a runtime exception is generated
However, the real difference is between as? and as: the former is an attempt to cast, the latter is a forced cast, resulting in runtime error if not possible.
Update Dec 14, 2015 Since Swift 1.2, there are 3 variations of the as operator:
as? is an attempt to cast, evaluating to nil if cast fails
as! is a forced cast, resulting to an runtime exception if cast fails (this is what as previously did)
as is now a special type of cast to be used when casting to equivalent types, usually bridged types, such as Swift's String and NSString.
From The Swift Programming Language book,
as is a type cast operator which we use to downcast to the subclass and as? is used for an optional form, when we are not sure if the downcast will succeed. Consider the following example
for item in library {
if let movie = item as? Movie {
println("Movie: '(movie.name)', dir. (movie.director)")
} else if let song = item as? Song {
println("Song: '(song.name)', by (song.artist)")
}
}
The example starts by trying to downcast the current item as a Movie. Because item is a MediaItem instance, it’s possible that it might be a Movie; equally, it’s also possible that it might be a Song, or even just a base MediaItem.
String? An optional value either contains a value or contains nil to indicate that the value is missing.
From this,
as? String means when you don't know what you're downcasting, you are assuming that as a String, but it might me Integer or Float or Array or Dictionary
as String? means it's an Optional Value, it may either contain a String or Nil value.
Yes there is a difference.
In the first case, you are doing an optional cast to the type String. This will return a value if the object you are attempting to cast is indeed a String or nil if it is not.
In the second case, you are doing a forced cast to the type String?. If the value you are casting is not a string, it will crash your program.
YES, there is diffrence.
variable as String? downcast to optional String.If variable is not String? it will cause run-time exception.
while variable as? String will return nil if your variable is not String type or return downcast variable to String. This is conditional downcasting, if you not sure about down-casting you need to use this .
var tf:TextFormat = myTextField.getTextFormat();
trace(typeof tf.color); // "number"
trace(tf.color is uint); // true
var myColor:uint = tf.color; // error: 1118: Implicit coercion of a value with static type Object to a possibly unrelated type Number.
Why?
var myColor:uint = int(tf.color); // works. But why do I have to cast it?
From Adobe's API reference:
color:Object
So color is type of Object, the second line traced out number as type because it was assigned by default or in code, but it does not necessarily mean that color can only be number. We can assign string type to color object as well, so type of tf.color can be a number or a String:
tf.color = "0x00ff00";
myTextField.setTextFormat(tf); // Change text color to green
If we compare the following two lines:
var myColor:uint = "0x00ff00"; // 1067: Implicit coercion of a value of type String to an unrelated type uint.
var myColor:uint = tf.color; // 1118: Implicit coercion of a value with static type Object to a possibly unrelated type Number.
// var myColor:uint = new Object(); // This line gives same 1118: Implicit coercion of a value with static type Object to a possibly unrelated type uint.
We can see that the compiler is complaining that it needs explicit instructions to perform the conversion. From this point, we have enough reason to believe that the compiler is designed the way it is. Also notice that you can use constructor of uint or int to convert Object to number. uint and int are both derived classes of Object.
var myColor:uint = new uint(tf.color);
I hope this shed light.
This question already has answers here:
The cast to value type 'Int32' failed because the materialized value is null
(8 answers)
Closed 6 years ago.
I have the following query:
int? Giver = Convert.ToInt32(db.vwAssignments.Sum(a => a.Amount));
but if there is no records that matches the search criteria then the following error will be raised
The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
pls help
The basics of defensive programming:
first assign the result of your Sum() operation to a nullable variable
object resultOfSum = db.vwAssignments.Sum(a => a.Amount);
check for NULL! and only if it's not null, then convert it to an INT
if(resultOfSum != null)
{
int Giver = Convert.ToInt32(resultOfSum);
}
Also: if your Amount field is a Int to start with, most likely this will already give you NULL or a valid Int - I think that call to Convert.ToInt32() is not necessary:
int? Giver = db.vwAssignments.Sum(a => a.Amount);
if(Giver.HasValue)
{
......
}