I have this code: ```val (term, definition) = stri...
# announcements
m
I have this code:
Copy code
val (term, definition) = string.split(" ")
val card = Card(term, definition)
I would like to do this:
Copy code
val card = Card(string.split(" "))
but it appears I cannot do that not even with using the spread operator (*) am I missing some thick? or no such luck?
m
Is
Card
your own class? If so, you could create a secondary constructor:
Copy code
data class Card(val term: String, val definition: String) {
  constructor(pieces: List<String>) : this(pieces[0], pieces[1]) {}
}

fun main() {
  println(Card("foo bar".split(" ")))
}
or a factory function:
Copy code
data class Card(val term: String, val definition: String)
  
fun Card(pieces: List<String>) = Card(pieces[0], pieces[1])

fun main() {
  println(Card("foo bar".split(" ")))
}
or a factory function in a companion object:
Copy code
data class Card(val term: String, val definition: String) {
  companion object {
    fun newInstance(pieces: List<String>) = Card(pieces[0], pieces[1])
  }
}

fun main() {
  println(Card.newInstance("foo bar".split(" ")))
}
m
question
I thought "factory" refers to a method that can return different subclasses of a base class
but here and in other contexts i've seen it basically refer to a method that returns an instance of a class
is there a more specific name for a method that returns one of several subclasses, depending on the arguments?
s
I mean, maybe just a generic factory? I don’t know if I’ve ever seen a more succinct term to describe what you’re talking about
a factory method is just a method that handles creation of an object for you, there isn’t necessarily any presumption of class hierarchy aside from the type of the parameters and the stated return type
☝️ 2
m
It doesn’t work the way you’d like because
split()
returns a List, while the spread operator works with arrays. Anyway, if your class accepts two parameters even the spread operator won’t work because your constructor function should be variadic , that means accept a variable number of arguments:
class Card(vararg args:String)