As mentioned in the comments, this code does not compile. It still has the following problems:
names
can be null
, so you'll either have to ensure that it isn't, which you could do using the Elvis operator:
val names = readLine()?.split("\n") ?: return
Or you can use a safe call on names
wherever you use it:
names?.chunked(group)
If you look at the documentation for chunked, you'll see that it has one parameter, size
of type Int
. However, you are passing a String
to it, which you've read from the user. You'll have to try to convert this string to an int before passing it into chunked:
val group = readLine()?.trim()?.split(" ")?.first()?.toInt() ?: return
Note that I'm trimming and splitting the user input to increase chances of retrieving a valid int.
Fixing these problems makes your code compile. However, there's one more thing to fix. Assuming you meant the newline character with /n
, you are now using the newline character as a separator for the names as well as to indicate that the user is done entering names. I suggest you use something different, like a comma. In total, this could give something like the following.
fun main() {
//receive names from user
print("Enter the names (separated by a comma): ")
val names = readLine()?.split(",")?.map { it.trim() }
//receive number of groups from the user
print("Enter number of groups: ")
val group = readLine()?.trim()?.split(" ")?.firstOrNull()?.toInt() ?: return
print(names?.chunked(group))
}