Reputation: 39
How to convert array of string to list of integers using val. I am using below code to do this
object ArraytoListobj {
def main(args :Array[String]) {
val intList :List[Int] = args.toList
println(intList)
}
}
When trying to compile the programme, I am getting below error.
scala:3: error: type mismatch;
found : List[String]
required: List[Int]
val intList :List[Int] = args.toList
one error found
Upvotes: 1
Views: 14082
Reputation: 149538
As of Scala 2.13.0, you can write:
val listOfInts: List[Int] = args.flatMap(_.toIntOption)
If you want to convert and discard any non Int
matching Strings:
val listOfInts: List[Int] = args.flatMap(i => Try(i.toInt).toOption).toList
Upvotes: 6
Reputation: 2686
You can just do that, if you are sure all the element in the args are going to be Int.
val strToInt = args.map(_.toInt).toList
println(strToInt)
Upvotes: 7