1

So I have this Java code:

String values = input.nextLine();
String[] longs = values.split(" ");

Which splits the string input into a string array.

I try it in Kotlin

var input: String? = readLine()
var ints: List<String>? = input.split(" ".toRegex())

and I get an error: "Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of the the type String?"

I am new to Kotlin and would like some clarity on how to do this. Thank you!

1
  • 1
    You should read the documentation about null safety. Commented Feb 2, 2018 at 20:49

2 Answers 2

9

If you have a look at readLine() it reveals that it might return null:

/**
 * Reads a line of input from the standard input stream.
 *
 * @return the line read or `null` if the input stream is redirected to a file and the end of file has been reached.
 */
public fun readLine(): String? = stdin.readLine()

Therefore it's not safe to call split on its result, you have to handle the null case, e.g. as follows:

val input: String? = readLine()
val ints: List<String>? = input?.split(" ".toRegex())

Other alternatives and further information can be found here.

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

2 Comments

Indeed, using !! is almost never the answer. Propagating nullability gives you a chance to handle any unexpected errors gracefully.
Updated. Thanks everyone!
1

Look, you code is almost right, just missed the !! this ensure that the string should not be empty (it will throw a error). You code should be like this:

val input: String? = readLine()
var ints: List<String>? = input!!.split(" ".toRegex())

Note that I just added !! operator and change var to val on line 1, because your input should not be changed (it was given by the user).

7 Comments

Thank you! That makes my code much cleaner than adding an if statement checking if it is null.
Question: what does the !! operator do? Is it basically a catch/throw for nulls?
@KevinPatrick, to answer your question, it does more than assert non-nullness; it also casts the expression to the left to a non-null type. It can also cast ambiguous types from calls to Java methods (e.g. a java function might return a String! which means "could be either a String? or a String") to a definite non-null type
I think a more correct answer would be to replace the !! with the safe navigation operator ?., because ints is a nullable type and ?. will return null if input is null, whereas !! will throw an exception if input is null, never resulting in a null being assigned to ints
If you want to see NullpointerException at runtime, go ahead and use !!
|

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.