Azmath Shaik
Azmath Shaik

Reputation: 39

Scala convert Array of string to List of Integers

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

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Edit:

As of Scala 2.13.0, you can write:

val listOfInts: List[Int] = args.flatMap(_.toIntOption) 

For Scala < 2.13

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

Raman Mishra
Raman Mishra

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

Related Questions