1

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
2
  • 2
    args.map(_.toInt).toList but it will throw if any String contains non-digit characters. Commented Feb 26, 2019 at 8:23
  • Thanks @ jwvh it solved my problem Commented Feb 26, 2019 at 8:54

2 Answers 2

7

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

3 Comments

I would love to improve my answer, if the person who downvoted let me know the problem.
Not the downvoter, but I guess this misses the fact that there may be strings in the array which are not parseable to an Int.
I explicitly mentioned that if you are sure that all the elements are Int so i don’t think that should be the reason
6

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

2 Comments

Thanq @ Yuval. I will try to implement this
in Scala 2.13 (which is still in milestones), you will be able to cut Try out of it and just args.flatMap(_.toIntOption)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.