August 15th, 2018

Converting List to Enumeration in Kotlin

There’s a bunch of helper extension methods that the Kotlin standard library provides for working with collections. However, it would seem that at the present moment java.util.Enumeration has been left a bit behind. Here is a simple extension method to convert any List to a matching Enumeration:

And here is how you can use it to expose the local file system to the JTree component. First, we create a custom implementation of the TreeNode interface:

Note a few language shortcuts that make the code more concise than its Java counterparts:

  • Since File.listFiles() can return null, we wrap that call with a simple Elvis operator: file.listFiles() ?: arrayOf().
  • The initializer block sorts the File children in place by name.
  • To return tree node enumeration in children(), we first map each File child to the corresponding FileTreeNode and then use our extension function to convert the resulting List to Enumeration.
  • Looking up the index of the specific node is done with the existing extension indexOfFirst function from the standard library.

Now all is left to do is to create our JTree: