3

first, I create empty Array(Kotlin) instance in companion object.

 companion object {
        var strarray: Array<String> = arrayOf()
        var objectarray: LinkedHashMap<Int, List<Any>> = LinkedHashMap<Int, List<Any>>()
    }

and I expected that I use empty array instance when read textString from CSV File.

 fun csvFileToString():String {

    val inputStream = File(Paths.get("").toAbsolutePath().toString()
            .plus("/src/main/SampleCSVFile_2kb.csv")).inputStream()
    val reader = inputStream.bufferedReader()
    var iterator = reader.lineSequence().iterator()
    var index:Int = 1;

    while (iterator.hasNext()){
        var lineText:String = iterator.next()
       strarray.set(index, lineText)
       index++
    }

    return ""
}

but when I run that source code

a.csvFileToString()
println(CsvParser.strarray)

occured exception

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
strarray.set(index, lineText) <<<<<<<<< because of this line

can I use Array(from kotlin collection) like ArrayList(from java collection)?

3 Answers 3

5

You can add a new item to an array using +=, for example: item += item

private var songs: Array<String> = arrayOf()
   fun add(input: String) {
        songs += input
    }
Sign up to request clarification or add additional context in comments.

Comments

4

Size of Array is defined at its creation and cannot be modified - in your example it equals 0.

If you want to create Array with dynamic size you should use ArrayList.

Comments

2
  • arrayOf gives you an array. Arrays have fixed length even in Java.

  • listOf gives you an immutable list. You cannot add or remove items in this list.

  • What you're looking for is mutableListOf<String>.

In your current approach, reusing a member property, don't forget to clear the list before every use.

Your code can be further simplified (and improved) like so:

out.clear()
inputStream.bufferedReader().use { reader -> // Use takes care of closing reader.
    val lines = reader.lineSequence()
    out.addAll(lines) // MutableList can add all from sequence.
}

Now imagine you wanted to consume the output list but needed to parse another file at the same time.

Consider working towards a pure function (no side effects, for now no accessing member properties) and simplifying it even further:

fun csvFileToString(): String { // Now method returns something useful.
    val inputStream = File(Paths.get("").toAbsolutePath().toString()
            .plus("/src/main/SampleCSVFile_2kb.csv")).inputStream()

    inputStream.bufferedReader().use {
        return it.lineSequence().joinToString("\n")
    }
}

In this case we can totally skip the lists and arrays and just read the text:

inputStream.bufferedReader().use {
    return it.readText()
}

I'm assuming that's what you wanted in the first place.

Kotlin has a lot of useful extension functions built-in. Look for them first.

2 Comments

I wouldn't call it a pure function as it does access external resources (csv file in this case)
@pwolaq I know, how to better describe it?

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.