How to convert string array to int array in scala

I am very new to Scala and I'm not sure how to do this. I didn’t succeed. suppose the code:

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

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

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

Thank you and apologize if the question is dumb.

+5
source share
2 answers

Applying a function to each element of the collection is performed 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)

, _.toInt x => x.toInt:

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

, , :

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
+9

Scala 2.13, String::toIntOption String Option[Int] , , , :

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

Source: https://habr.com/ru/post/1584795/


All Articles