1

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?

1
  • I need to create an instance of a class using an array of values - could you please explain why you need that? It looks quite brittle Commented Feb 5, 2022 at 23:34

1 Answer 1

2

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?).

Sign up to request clarification or add additional context in comments.

3 Comments

Mmm. Another reason to avoid this is the lack of documentation/readability. When you call a constructor, your IDE can show you (via tooltips or hints or whatever) the names of the parameter(s), and any doc comment(s) attached to them. For the primary constructor, that would be very informative; not so for the secondary one.
(In fact, if you wanted to make it even clearer, you could provide the parameter names when calling the primary constructor, e.g. Person(name = "Fred", lastName = "Bloggs"), and even give the parameters in any order; the secondary constructor doesn't let you do either of those.)
I agree with @gidds on this. I guess I would first advise to use values[0] and values[1] as arguments on the call site before suggesting declaring such a constructor. Not sure whether the OP needs this in several places or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.