9

I'd like to convert an Array[String] to an Array[Int], using map method. What is the shortest way to get a function of type (String) => Int to pass as map argument?

I'd prefer convert existing builtin ones like Integer.valueOf in some way. A method of argument binding to shorten the construction like def parseInt(s:String) = Integer.parseInt(s, 10) would also be great.

4 Answers 4

17
scala> Array("1", "2", "3") map(_.toInt)
res4: Array[Int] = Array(1, 2, 3)

or

scala> def parseInt(s:String) = Integer.parseInt(s, 10)
parseInt: (s: String)Int

scala> Array("1", "2", "3") map parseInt
res7: Array[Int] = Array(1, 2, 3)
Sign up to request clarification or add additional context in comments.

3 Comments

What does "" from ".toInt" mean?
It is a placeholder, equivalent to Array("1", "2", "3") map (x => x.toInt), which means "for each element in array, apply .toInt method on it, and construct a new array", which will result in Array("1".toInt, "2".toInt, "3".toInt)
This is a good resource on Scala's "Placeholder Syntax": books.google.co.uk/…
3

First, let's define an array of strings:

scala> val foo = Array("1", "2", "3")
foo: Array[java.lang.String] = Array(1, 2, 3)

The most obvious way would be to use Scala's toInt(), available on strings:

Definition:

// StringLike.scala
def toInt: Int         = java.lang.Integer.parseInt(toString)

(Note: toString, defined elsewhere, simply converts the StringLike object to a Java string)

Your code:

scala> foo.map(_.toInt)
res0: Array[Int] = Array(1, 2, 3)

Integer.valueOf() also works, but notice you will get Array[Integer] instead of Array[Int]:

scala> foo.map(Integer.valueOf)
res1: Array[java.lang.Integer] = Array(1, 2, 3)

While we're at it, a for comprehension would work almost as well, except you'd be invoking toInt yourself, instead of passing it over to map()

scala> for (i<-foo) yield i.toInt
res2: Array[Int] = Array(1, 2, 3)

Comments

2

It's as simple as:

Array("1", "2", "3") map Integer.valueOf

Comments

0
scala> val strs = Array("1", "2")
strs: Array[java.lang.String] = Array(1, 2)

scala> strs.map(_.toInt)
res0: Array[Int] = Array(1, 2)

Comments

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.