Home > Back-end >  Problem in Kotlin with inserting Int array elements into String list using For loop (toString is use
Problem in Kotlin with inserting Int array elements into String list using For loop (toString is use

Time:01-01

Kotlin problem:

  1. Create an integer array of numbers called numbers, from 11 to 15.
  2. Create an empty mutable list for Strings.
  3. Write a for loop that loops over the array and adds the string representation of each number to the list.

I have tried the following:

import java.util.*
var numbers = intArrayOf(11,12,13,14,15)
var myList = mutableListOf<String>()
for (element in numbers) {
    myList.add(Arrays.toString(element))
}

But it gives me an error:

error: none of the following functions can be called with the arguments supplied: 
public open fun toString(p0: Array<(out) Any!>!): String! defined in java.util.Arrays
public open fun toString(p0: BooleanArray!): String! defined in java.util.Arrays
public open fun toString(p0: ByteArray!): String! defined in java.util.Arrays
public open fun toString(p0: CharArray!): String! defined in java.util.Arrays
public open fun toString(p0: DoubleArray!): String! defined in java.util.Arrays
public open fun toString(p0: FloatArray!): String! defined in java.util.Arrays
public open fun toString(p0: IntArray!): String! defined in java.util.Arrays
public open fun toString(p0: LongArray!): String! defined in java.util.Arrays
public open fun toString(p0: ShortArray!): String! defined in java.util.Arrays
    myList.add(Arrays.toString(element))
                      ^

Later I solved the problem with

myList.add(Arrays.toString(numbers))

Why first code didn't work?

CodePudding user response:

Arrays.toString() is for converting an entire Array of data into a single String, so it's not the right tool for your task anyway. (If you were going to do this, in Kotlin, it should be preferred to call joinToString() on the Array instead of using Java's Arrays utility class.)

You want to convert each individual Int into a String one at a time, so you should use:

myList.add(element.toString())

CodePudding user response:

Your first method doesn't work because Arrays.toString takes an array and converts it to a string, as you can see from all the overloads listed in the error message. element is not an array - it is an element of the numbers array, i.e. an Int. Therefore your first way doesn't work.

Note that your second way adds the single string "[11, 12, 13, 14, 15]", rather than the 5 strings "11", "12", "13", "14", "15" to the list. If you want to add those 5 strings, you should call toString on element:

for (element in numbers) {
    myList.add(element.toString())
}

Also, it is not recommended to use the Java Arrays.toString method. If you want to produce the string "[11, 12, 13, 14, 15]", use numbers.contentToString() instead.

  • Related