10

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.

2 Answers 2

17

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
Sign up to request clarification or add additional context in comments.

Comments

0

Starting Scala 2.13, you might want to use String::toIntOption in order to safely cast Strings to Option[Int]s and thus also handle items that can't be cast:

Array("1", "12", "abc", "123").flatMap(_.toIntOption)
// Array[Int] = Array(1, 12, 123)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.