Scala return type for tuple-functions

44,755

Solution 1

def foo : (Int, String, String) = (1, "Hello", "World")

The compiler will interpret the type (Int, String, String) as a Tuple3[Int, String, String]

Solution 2

Also, you can create a type alias if you get tired of writing (Int,String,String)

type HelloWorld = (Int,String,String)
...

def foo : HelloWorld = (1, "Hello", "World")
/// and even this is you want to make it more OOish
def bar : HelloWorld = HelloWorld(1, "Hello", "World")
Share:
44,755

Related videos on Youtube

Felix
Author by

Felix

<3 Scala Consider visiting my scala blog: A Scala from 0 to 1

Updated on March 25, 2020

Comments

  • Felix
    Felix about 4 years

    I want to make a scala function which returns a scala tuple.

    I can do a function like this:

    def foo = (1,"hello","world")
    

    and this will work fine, but now I want to tell the compiler what I expect to be returned from the function instead of using the built in type inference (after all, I have no idea what a (1,"hello","world") is).

    • Felix
      Felix about 14 years
      OK, folks...I blame the compiler for not giving me any useful information. I forgot to put the = sign, hence I got tons of errors. If anyone comes with an elaborate answer I will accept it though, the correct way was: def foo:Tuple[Int,String,String] = (1,"hello","world")
    • Felix
      Felix about 14 years
      Tuple3[...] even, remember to put the# of items in the class name (max 22ish)