0

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?

2
  • Assuming availableComPorts is a List<ComPort>, you simply want availableComPorts.map(ComPort::portName).toTypedArray(), is that what you're asking?
    – JB Nizet
    Jun 28, 2018 at 19:04
  • That is what I'm asking, correct. And that solution does work! Funnily enough I was close on an attempt I had but my syntax was slightly wrong. Thank you!
    – StuJ
    Jun 28, 2018 at 19:09

1 Answer 1

3

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.

2
  • That works, thank you very much! The ComPort::portName is what tripped me up on a previous attempt, so thank you very much for the clarification.
    – StuJ
    Jun 28, 2018 at 19:10
  • 1
    You're welcome! Lambda syntax in Kotlin look quite similar to ones in Java if you're familiar with it. Anyway official doc might be helpful.
    – zavyrylin
    Jun 28, 2018 at 19:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.