Home > other >  Loop-ing mutiple values with the use of 1 instance from a data class
Loop-ing mutiple values with the use of 1 instance from a data class

Time:09-22

I am trying to figure out how to loop a data class. I have a function called getAges() which contains a listof Ages from 1 - 10. Each age are called from a data class called Age, which should be an Int. How can I successfully loop through Age with different numbers, for ex 1-10? Appreciate the feedback!

My Data class:

@Entity(tableName = "dropdown_age")
data class Age(

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "age")
    val age: Int?
)

My Function called getAges:

class ProfileViewModel: Viewmodel() {
    fun getAges() = listOf(

        Age(1), Age(2), Age(3), Age(4), Age(5),
        Age(6), Age(7), Age(8), Age(9), Age(10),

                         )
}

CodePudding user response:

There is a List "constructor" function that can be used to create a List using a lambda where the lambda parameter is an index, starting at 0. (I use quotation marks for constructor because interfaces don't have true constructors. This is just a function that looks like a constructor because of how it is capitalized.)

fun getAges() = List(10) { Age(it   1) }

Or you can use the map function with a range. map modifies each item out of any Iterable to produce a new List.

fun getAges() = (1..10).map { Age(it) }

// or

fun getAges() = (1..10).map(::Age)

CodePudding user response:

Using collections api forEach

 getAges().forEach{
     println(it.age)
 }

Or using normal For loop

 for (age: Age in getAges()) {
     println(age.age)
 }
  • Related