Reputation: 101
Is there a way to code something like this in kotlin for a variable number of ints? For example the input should be "1 3 5" or "3 2 2 7" (String with space-separated Ints). And I am not allowed to use java librarys.
val (x, y) = readLine()!!.split(' ').map(String::toInt)
println(x+y)
Thanks in advance.
Upvotes: 2
Views: 811
Reputation: 40078
If you want to just print each string, then you can use forEach
readLine()!!.split(' ').forEach{ println(it) }
If you want to print as int, then you can use forEach
with toInt()
readLine()!!.split(' ').forEach{ println(it.toInt()) }
Or if you want sum you can use sumBy directly
readLine()!!.split(' ').sumBy{ it.toInt() }
Upvotes: 2
Reputation: 101
Found a solution for my problem:
var list: List<Int> = readLine()!!.split(' ').map(String::toInt)
for(m in list){
println(m)
}
Upvotes: 0