Home > Mobile >  How to instance a class using array | Kotlin
How to instance a class using array | Kotlin

Time:02-06

I need to create an instance of a class using an array of values.

  • I know how much parameters the class have
  • All class parameters are string

I tried:

class Person(val name: String, val lastName: String)
{

}

fun main()
{
   val values= listOf<String>("James", "Smith")
   val myPerson = Person(values);
}

Is possibly do something like that?

CodePudding user response:

You could create a custom constructor that takes a list and uses it to instantiate your class:

class Person(val name: String, val lastName: String) {
    constructor(values: List<String>) : this(values[0], values[1])
}

However, I would say you should avoid this since it is very error-prone (what if the provided values list is empty or have only one element?).

  •  Tags:  
  • Related