2

Normally if I am reading a line of input from stdin that looks like "100 200" I can store them both as ints with this line:

val Array(a, b) = readLine.split(" ").map(_.toInt);

But what if a is an integer and b is a string?

1
  • well if the types are different you cannot store them in an homogeneous container such as an Array. If you know the cardinality just put them in variables Commented Jun 10, 2015 at 18:29

2 Answers 2

2

You cannot store values of different types into an homogeneous container such as an Array. If you know the cardinality, just store them in separate variables.

val input = "100 foo"
val Array(a, b) = input.split(" ")

val p1 = scala.util.Try(a.toInt)
val p2 = b

I used scala.util.Try because toInt may fail and throw an exception

Sign up to request clarification or add additional context in comments.

Comments

-1
val readLine = "100 foo"
val (int, str) = readLine.split(" ") match {case Array(i, s) => (i.toInt, s)}

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.