2

I'm coding in kotlin, and i have a problem with the Arrays

I would make a function that return an Array of Car (for example), but that array is build by data from file

Exemple :

fun buildAllCar(data:string) : Array<Car> {
    val array = arrayOfNulls<Location>(5) //In the real code, the size is retrieved by an other item

    for(i in array.indices){
        array[i] = buildACarByData(data); //Just so you could see a sample usage
    }

    return array.requireNoNulls()
}

Without the requireNoNulls() , the type of object returned is Array of Car? Use this method is the only way to get an Array of Car or there is a other way?

Thanks for your help

2
  • buildAllCar is having return type as Array of car and varible array is of type array of Location. Also please explain more about your problem Commented Feb 14, 2020 at 17:19
  • Does it need to be an Array? A List would seem to be more appropriate. (Arrays are needed for backward compatibility, but lists are more flexible and powerful and better for most things.) Commented Feb 14, 2020 at 21:33

2 Answers 2

2

You can initialize an array in Kotlin using a mapper function like so

val array = Array(size, mapper function)

So to construct an Array of non-nullable Car

fun buildAllCar(data: String): Array<Car> = Array(5) { buildACarByData(data) }
Sign up to request clarification or add additional context in comments.

Comments

0

Change the code and modify return type of Array because when you apply return type, Kotlin check the nullablity so "?" define with safe call and return list if if the array list objects are null.

fun buildAllCar(data:string) : Array<Car?> {
    val array = arrayOfNulls<Location>(5) //In the real code, the size is retrieved by an other item

    for(i in array.indices){
        array[i] = buildACarByData(data); //Just so you could see a sample usage
    }

    return array
}

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.