0

I'm trying to read a single line from the console, convert entered numbers to Integers, and add them to

Array<Int>

The shortest one-liner I came up with is

val na: Array<Int> = readLine()!!.split(' ').map{it.toInt()}.toTypedArray() // Array<Int>

This is much longer than e.g python version below. Is it possible to write a shorter code to achieve the same result? This would matter in the compativive programming.

na = [int(i) for i in input().split(' ')]
2
  • right python version shortest than kotlin, but kotlin's snippet more readable! Commented Apr 19, 2018 at 12:02
  • Unless you are competing in codegolf the size shouldn't matter that much Commented Apr 19, 2018 at 12:08

2 Answers 2

3

You don't really need to declare the variable type, so:

val na = readLine()!!.split(' ').map { it.toInt() }.toTypedArray()

Does it have to be an array? Why can't you use a list? It'll probably be the same thing to you and you won't even notice the difference (if any at all). You'll be able to iterate over it the same way. For a list, you can have:

val na = readLine()!!.split(' ').map { it.toInt() }

I guess there's no way of making it shorter. readLine is longer than input, toInt is longer than int, and it is longer than i... there's not much more to do now. And it shouldn't matter, actually ;)

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

Comments

1

Your Python version doesn't give you an array, it gives a list. Well, so does

val na = readLine()!!.split(' ').map{it.toInt()}

which is only longer then Python by a few characters.

Comments

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.