2

I try to use (1,), but doesn't work, what's the syntax to define Tuple1 in scala ?

scala> val a=(1,)
<console>:1: error: illegal start of simple expression
       val a=(1,)
1
  • you mean, you want more convenient syntax than Tuple1(1) ? Commented Nov 30, 2015 at 3:45

3 Answers 3

11

For tuple with cardinality 2 or more, you can use parentheses, however for with cardinality 1, you need to use Tuple1:

scala> val tuple1 = Tuple1(1)
tuple1: (Int,) = (1,)

scala> val tuple2 = ('a', 1)
tuple2: (Char, Int) = (a,1)

scala> val tuple3 = ('a', 1, "name")
tuple3: (Char, Int, java.lang.String) = (a,1,name)

scala> tuple1._1
res0: Int = 1
scala> tuple2._2
res1: Int = 1
scala> tuple3._1
res2: Char = a
scala> tuple3._3
res3: String = name

To declare the type, use Tuple1[T], for example val t : Tuple1[Int] = Tuple1(22)

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

Comments

2

A tuple is, by definition, an ordered list of elements. While Tuple1 exists, I haven't seen it used explicitly given you'd normally use a single element. Nevertheless, there is no sugar, you need to use Tuple1(1).

Comments

0

There is a valid use case in Spark that requires Tuple1: create a dataframe with one column.

import org.apache.spark.ml.linalg.Vectors

val data = Seq(
    Vectors.sparse(5, Seq((1, 1.0), (3, 7.0))),
    Vectors.dense(2.0, 0.0, 3.0, 4.0, 5.0),
    Vectors.dense(4.0, 0.0, 0.0, 6.0, 7.0)
  )
data.toDF("features").show()

It will throw an error: "value toDF is not a member of Seq[org.apache.spark.ml.linalg.Vector]"

To make it work, we have to convert each row to Tuple1:

val data = Seq(
    Tuple1(Vectors.sparse(5, Seq((1, 1.0), (3, 7.0)))),
    Tuple1(Vectors.dense(2.0, 0.0, 3.0, 4.0, 5.0)),
    Tuple1(Vectors.dense(4.0, 0.0, 0.0, 6.0, 7.0))
  )

or a better way:

val data = Seq(
    Vectors.sparse(5, Seq((1, 1.0), (3, 7.0))),
    Vectors.dense(2.0, 0.0, 3.0, 4.0, 5.0),
    Vectors.dense(4.0, 0.0, 0.0, 6.0, 7.0)
  ).map(Tuple1.apply)

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.