Scala Convert List of Strings to Ints, List[String] => List[Int]

Posted on Monday, May 12, 2014


I am still fairly new to Scala so take what I write in this article with a grain of salt.


The more I learn Scala to more I like it and here is an example of why…

The following Scala Code will read in a file (whos name is the first command line argument) and read in every line as a String Array, convert it to a List[String] then convert that to a List[Int]  (this assumes the file has a valid integer on each line.  Then it prints out the Int list adding +1 to each number as it prints it out.


 
import scala.io.Source

object ListStringToInt{

  def main(args: Array[String]) {
    val sList = Source.fromFile(args(0)).
      getLines.toList.map((s: String) => s.toInt)

    sList.foreach((x: Int) => println(x + 1))
  }
}




I like this line, it simple and short.


 
    val sList = Source.fromFile(args(0)).
      getLines.toList.map((s: String) => s.toInt)


Going over it bit by bit

Read from a file

 
    Source.fromFile(args(0))



Get the Lines from the file and convert them into a list, this is a List of Strings

   getLines.toList.



Take the List of Strings and convert it to a List of Ints by running each String in the list through the function (s: String) => s.toInt

      
   .map((s: String) => s.toInt)


This portion of the code can be further simplified by writing it in the following way

      
   .map(_.toInt)



Cleaning up the rest of the code you get the following


import scala.io.Source
/**
 * Created by patman on 5/12/2014.
 */
object ListStringToInt{

  def main(args: Array[String]) {
    val sList = Source.fromFile(args(0)).getLines.toList.map(_.toInt)
    sList.foreach(x => println(x + 1))
  }
}


I think this simple one liner is very effective and easy to read once you become a little familiar with Scala (I am by no means an expert yet)

I have been guilty of creating one liners in code that, though they are concise, are difficult to read.  I think the Scala language and libraries do a very good job in making readable one liners.




References



No comments:

Post a Comment