Why is this not adding my 2 variables together lol
# getting-started
s
Why is this not adding my 2 variables together lol
f
What's the return type of
readLine()
?
s
It shukd be int do I thought it woukd infer that
f
Documentation says it's
String?
-- which would explain why
"3" + "5" == "35"
You can, for example, try using
?.toInt()
on the inputs
plus1 2
d
It looks like it is adding, but the expected output is multiplying.
Oh, never mind, Richard is correct, and I'm just misreading it.
f
While Kotlin is great at inferring types, it needs enough information to do that. The
operator fun plus
is defined both for `Int`s and for `String`s, so there is no reason in your original code for Kotlin to think you're not talking about `String`s
2
s
Thanks !!
I swear I have does it this way before bu T I guess not
k
readLine()
returns a
String?
.
readLine()?.toInt()
returns an
Int?
. There is no
+
operator between nullable
Int?
types; you'd have to use
readLine()!!.toInt()
or the shorter, more readable form:
readln().toInt()
.
d
or the more appropriate
readLine()?.toIntOrNull() ?: error("unable to read integer")
Edit: Never mind, I'm sleepy.
f
Good catch, @Klitos Kyriacou!
k
> or the more appropriate
readLine()?.toIntOrNull() ?: error("unable to read integer")
Why? Just
readln().toInt()
alone gives you much more appropriate error messages than the cryptic
IllegalStateException
that
error
produces.
👍 1
d
Fair enough.
I'm not fully awake 😉
s
Lemme play with this once my boss ain't looking haja
It only worked will non nullable. The only safe ? Still failed
This is the error when I try the only safe
k
This is exactly what I was talking about in my first message. TL;DR: don't use
readLine()?.toInt()
, use
readln().toInt()
.
f
Yes, that is what Klitos said earlier:
readLine()
doesn't give you a
String
, but a
String?
-- meaning that it could be a
String
or
null
. The null-safe accessor
?.
then says "If the left-hand side is not
null
, access the right-hand side (
toInt()
in this case) and use its result; otherwise, just keep using
null
for whatever code comes next."
String.toInt()
would give you an
Int
, but because of the
?.
instead of just
.
, a
null
-value
String
would mean "[...] just keep using
null
for whatever code comes next" in the above description. Thus, you end up with the type
Int?
-- something that could be an
Int
or
null
. The default implementation knows how to add two
Int
values together, but is not defined for adding a number to the Endless Void, so the compiler will only let you use it when the value is guaranteed to not be
null
. This is what various of the aforementioned code snippets do: Prevent your first
var
from being able to become
null
, and thus forcing its type to be
Int
rather than
Int?
.
1
Aaaand Klitos was slightly faster than I was 🙃
k
But that's a good, much fuller, explanation.
s
Your guys are awesome, thank you
I didn't realize readLine() was so old lol