Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a function that returns multiple values in Scala [duplicate]

I am a new developer on Spark & Scala and I want to do an easy thing (I think..) :

  • I have 3 int values
  • I want to define a function that returns the result of an SQL request (as a DF containing 3 columns)
  • I want to store the content of each of those 3 columns in my 3 initial variables.

So, my code looks like this :

var a
var b 
var c

def myfunction() : (Int, Int, Int) = {
  val tmp = spark.sql(""" select col1, col2, col3 from table
  LIMIT 1
  """)

  return (tmp.collect(0)(0), tmp.collect(0)(1), tmp.collect(0)(2))

}

So, the idea if to call my function like this :

a, b, c = myfunction()

I tried a lot of configurations but I get many different errors each time, so, I got confused.

like image 767
salamanka44 Avatar asked Apr 25 '26 06:04

salamanka44


1 Answers

You could just use destructuring bind. Since your method returns tuple you can unpack it using pattern matching:

val (a, b, c) = myfunction()

a, b and c will contain consecutive elements of the tuple.

like image 169
Krzysztof Atłasik Avatar answered Apr 28 '26 03:04

Krzysztof Atłasik