mplain
05/31/2020, 5:22 PMval (term, definition) = string.split(" ")
val card = Card(term, definition)
I would like to do this:
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?Mark Murphy
05/31/2020, 5:51 PMCard
your own class? If so, you could create a secondary constructor:
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:
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:
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(" ")))
}
mplain
05/31/2020, 7:02 PMmplain
05/31/2020, 7:03 PMmplain
05/31/2020, 7:03 PMmplain
05/31/2020, 7:04 PMShawn
05/31/2020, 7:14 PMShawn
05/31/2020, 7:16 PMMatteo Mirk
06/01/2020, 7:51 AMsplit()
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)