galaxigirl
galaxigirl

Reputation: 2550

Check for null row before adding to map

The following method throws an exception, since a splitRow can be empty

  private fun parseIt(data: String) =
    data
        .split("\n")
        .let { dataRows ->
            dataRows.map { dataRow ->
                dataRow.let {  dataRow.split("=")}.let { splitRow ->
                    splitRow[0] to splitRow[1].replace(";", "")
                }
            }
        }.toMap()

How can I check if splitRow is not empty before retrieving it's elements?

Upvotes: 0

Views: 62

Answers (1)

Tenfour04
Tenfour04

Reputation: 93902

mapNotNull to skip some elements. takeIf to use null for invalid rows.

data.split("\n")
    .mapNotNull { dataRow ->
        dataRow.split("=")
            .takeIf { it.size >= 2 }
            ?.let { splitRow ->
                splitRow[0] to splitRow[1].replace(";", "")
            }
    }.toMap()

Upvotes: 1

Related Questions