StuJ
StuJ

Reputation: 26

Kotlin - lambda to return list of member variables

Preface: This is something I'm not sure Kotlin can do, but I feel like it should be able to do.

Question: Is it possible to return a list composed from another lists' member variables without creating a separate function, via lambda, mapping, or otherwise?

I have a Kotlin inner class that has a name string representing a physical COM port. I have a routine that will poll for available COM ports on a device, and will return a list of the available port name strings for selection.

inner class ComPort() {

val portName: String = "something"

... }

...


ComPortSelectBox.setItems(*getComPortNames())

...

private fun getComPortNames(): Array<String> {
  val names: ArrayList<String> = ArrayList()

  for(comPort in availableComPorts)
    { names + comPort.portName }

  return names.toTypedArray()
}

Because getComPortNames() is only used in the one location, I would love to simplify this call into something equivalent to getComPortNames that I can use inline within .setItems(...). Is this possible within Kotlin? If so, how would one do it?

Upvotes: 0

Views: 592

Answers (1)

zavyrylin
zavyrylin

Reputation: 342

I'm not sure what availableComPorts actually is, but it looks like Iterable. If so then you may do something like:

ComPortSelectBox.setItems(*availableComPorts.map(ComPort::portName).toTypedArray())

UPD. You did't mention which Java you're using. I assumed it is Java 8.

Upvotes: 3

Related Questions