Converting Array to List in Scala

Now, this has to have a built-in somewhere in Scala, because it just seems too common. So, how to convert an Array to a List in Scala?

Why do I need this? I needed to drop to Java for some functionality, which in this case returns an Array. I wanted to get that Array into a List to practice my functional programming skillz.

**Update**: I figured out how to convert Arrays to Lists the Scala way. Turns out it's a piece of cake.

val myList = List.fromArray(Array("one", "two", "three"))

or

val myList = Array("one","two","three").elements.toList

The call to elements returns an Iterator, and from there you can convert to a List via toList. Nice.

Because my first version wasn't actually tail recursive, what follows is a true tail recursive solution, if I were to implement this by hand. The above, built in mechanism is much better, though.


object ArrayUtil {
def toList[a](array: Array[a]): List[a] = {
def convert(arr: Array[a], aggregator: List[a]): List[a] = {
if (arr == null || arr.length == 0) aggregator
else convert(arr.slice(0, arr.length-1), arr(arr.length-1) :: aggregator)
}
convert(array, Nil)
}
}


The above code is interesting because it demonstrates a nested function. The convert function is nested inside toList. Scala encourages the decomposition of your problem into smaller and smaller functions.

*What follows is my original attempt.* Left here for a historical, "what not to do" perspective.

Here's my implementation of it, but if you know if there's a built-in function already implemented, please let me know.


object ArrayUtil {
def toList[a](array: Array[a]): List[a] = {
if (array == null || array.length == 0) Nil
else if (array.length == 1) List(array(0))
else array(0) :: toList(array.slice(1, array.length))
}
}


To quickly explain this, an object in Scala is a singleton instance of its class. The method toList is parameterized with type a. This is similar to generics in Java. Lastly, the :: operator (pronouned cons in Scala) creates a new List from a single item (the head, on the left) and another List (the tail, on the right). Oh, and Nil represents an empty List.

Popular posts from this blog

Lists and arrays in Dart

Null-aware operators in Dart