0

i am a newbie in scala, here i have an array variable call colarr

colarr: Array[(String, String)] = Array((empid,IntegerType), (empname,StringType), (address,StringType), (salary,IntegerType), (doj,TimestampType))

how to get individual value like empid and IntergerType from it?

6
  • 1
    What exactly is you're trying to do? Get a single value? Get some of the values? Do elaborate. Commented Jan 5, 2017 at 13:17
  • colarr.toMap.get(empid)? Commented Jan 5, 2017 at 13:18
  • these are column and datatype of table so i need to get the value and check its datatype Commented Jan 5, 2017 at 13:19
  • thanks Tzach, but how to iterate over each value and also it is not working it is showing error like <console>:48: error: not found: value empid colarr.toMap.get(empid) Commented Jan 5, 2017 at 13:20
  • collar.map { case (id, t) => ... } ? Commented Jan 5, 2017 at 13:24

1 Answer 1

3

If you want to go over each tuple, you can use Array.foreach:

scala> val arr = Array(("hello", "world"), ("this", "isnice"), ("yay", "it works"))
scala> arr.foreach { 
        case (first, second) => println(s"First element $first, Second element: $second") }

First element hello, Second element: world
First element this, Second element: isnice
First element yay, Second element: it works

If you want to project a value from each tuple, you can use Array.map:

scala> arr.map { case (first, second) => s"$first, $second" }
res1: Array[String] = Array(hello, world, this, isnice, yay, it works)

The case (first, second) is just syntax for creating a partial function which allows you to extract the first and second element from the tuple.

If you want something simpler for starters, you can a total function and work with _.1 and _.2 elements of the tuple:

scala> arr.map(tuple => s"${tuple._1}, ${tuple._2}")
res2: Array[String] = Array(hello, world, this, isnice, yay, it works)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you Yuval, i could able to get the value.
@anand arr.foreach { case (first, second) => if (first == value) { // Do stuff } }
Yuval is there any way to check if $second is numeric ??
What is the type or the tuple?

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.