Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string array to int array in scala

I am very new to Scala, and I am not sure how this is done. I have googled it with no luck. let us assume the code is:

var arr = readLine().split(" ")

Now arr is a string array. Assuming I know that the line I input is a series of numbers e.g. 1 2 3 4, I want to convert arr to an Int (or int) array.

I know that I can convert individual elements with .toInt, but I want to convert the whole array.

Thank you and apologies if the question is dumb.

like image 615
Mohammad Gharehyazie Avatar asked Apr 26 '15 21:04

Mohammad Gharehyazie


1 Answers

Applying a function to every element of a collection is done using .map :

scala> val arr = Array("1", "12", "123")
arr: Array[String] = Array(1, 12, 123)

scala> val intArr = arr.map(_.toInt)
intArr: Array[Int] = Array(1, 12, 123)

Note that the _.toInt notation is equivalent to x => x.toInt :

scala> val intArr = arr.map(x => x.toInt)
intArr: Array[Int] = Array(1, 12, 123)

Obviously this will raise an exception if one of the element is not an integer :

scala> val arr = Array("1", "12", "123", "NaN")
arr: Array[String] = Array(1, 12, 123, NaN)

scala> val intArr = arr.map(_.toInt)
java.lang.NumberFormatException: For input string: "NaN"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.lang.Integer.parseInt(Integer.java:580)
  at java.lang.Integer.parseInt(Integer.java:615)
  at scala.collection.immutable.StringLike$class.toInt(StringLike.scala:272)
  ...
  ... 33 elided
like image 77
Marth Avatar answered Sep 26 '22 03:09

Marth