ShrikeThe
ShrikeThe

Reputation: 89

init function for initializing List in Kotlin

I am trying to give init function some extra handling using the if else conditions:

val allDates = List<String>(daysInMonth) { "0$it" if(it/10 == 0) else it.toString() })

This is not a valid syntax for the init function and there seems to be very little information on this out there. Any suggestions on how to do this?

Upvotes: 0

Views: 641

Answers (2)

indra lesmana
indra lesmana

Reputation: 261

if you want declare first array allDates

the init for allDates like this

val daysInMonth = 30
    val allDates = arrayListOf<String>()
    for(i in 1..daysInMonth){
        if(i/10 == 0){
            allDates.add("0$i")
        }else{
            allDates.add("$i")
        }
    }

Upvotes: 0

Sharon
Sharon

Reputation: 598

it looks like your if statement is wrongly formated, try this

val allDates = List<String>(daysInMonth) {  if(it/10 == 0) "0$it" else it.toString() }

Upvotes: 2

Related Questions