Sebastian
06/28/2024, 4:45 PMFRQDO
06/28/2024, 4:45 PMreadLine() ?Sebastian
06/28/2024, 4:46 PMFRQDO
06/28/2024, 4:49 PMString? -- which would explain why "3" + "5" == "35"
You can, for example, try using ?.toInt() on the inputsDaniel Pitts
06/28/2024, 4:51 PMDaniel Pitts
06/28/2024, 4:52 PMFRQDO
06/28/2024, 4:52 PMoperator 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`sSebastian
06/28/2024, 4:53 PMSebastian
06/28/2024, 4:53 PMKlitos Kyriacou
06/28/2024, 4:55 PMreadLine() 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().Daniel Pitts
06/28/2024, 4:56 PMreadLine()?.toIntOrNull() ?: error("unable to read integer")FRQDO
06/28/2024, 4:58 PMKlitos Kyriacou
06/28/2024, 5:01 PMreadLine()?.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.Daniel Pitts
06/28/2024, 5:01 PMDaniel Pitts
06/28/2024, 5:01 PMSebastian
06/28/2024, 5:02 PMSebastian
06/28/2024, 5:32 PMSebastian
06/28/2024, 5:40 PMKlitos Kyriacou
06/28/2024, 5:47 PMreadLine()?.toInt(), use readln().toInt().FRQDO
06/28/2024, 5:48 PMreadLine() 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?.FRQDO
06/28/2024, 5:48 PMKlitos Kyriacou
06/28/2024, 5:49 PMSebastian
06/28/2024, 5:49 PMSebastian
06/28/2024, 6:09 PM