Reputation: 41
I need to create an instance of a class using an array of values.
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?
Upvotes: 1
Views: 230
Reputation: 17510
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?).
Upvotes: 2