Scala, generic tuple

scala list to tuple
scala shapeless
scala tuple
scala tuple to case class
scala tuple as parameter
scala append to tuple
scala array to tuple
scala tuple api

I have a generic method that can accept any tuple of any size, the only constraint is that the first element of this tuple should be of type MyClass.

Something like this:

trait MyTrait[T <: (MyClass, _*)] {
  getMyClass(x: T): MyClass = x._1
}

I've tried this

trait MyTrait[T <: (MyClass, _) with (MyClass, _, _) with (MyClass, _, _) with ...] {
  getMyClass(x: T): MyClass = x._1
}

but I get the error unboud wildcard type

It's a little bit unsafe but you can use Structural type in this case:

trait MyTrait {
  def getMyClass(x: {def _1: MyClass}): MyClass = x._1
}

Tuples | Tour of Scala, In Scala, a tuple is a value that contains a fixed number of elements, each with a distinct type. Tuples are immutable. Tuples are especially handy for returning  Scala tuple combines a fixed number of items together so that they can be passed around as a whole. Unlike an array or list, a tuple can hold objects with different types but they are also immutable. The following is an example of a tuple holding an integer, a string, and the console. val t = (1, "hello", Console)

If you want to do this without either boilerplate or runtime reflection, Shapeless is your best bet. You can use the IsComposite type class to put type-level constraints on the first element of a tuple:

import shapeless.ops.tuple.IsComposite

trait MustBeFirst

class MyClass[P <: Product](p: P)(implicit ev: IsComposite[P] { type H = MustBeFirst }) {
  def getMustBeFirst(x: P): MustBeFirst = ev.head(p)
}

And then:

scala> val good2 = (new MustBeFirst {}, "")
good2: (MustBeFirst, String) = ($anon$1@7294acee,"")

scala> val good3 = (new MustBeFirst {}, "", 123)
good3: (MustBeFirst, String, Int) = ($anon$1@6eff9288,"",123)

scala> val good4 = (new MustBeFirst {}, "", 'xyz, 123)
good4: (MustBeFirst, String, Symbol, Int) = ($anon$1@108cdf99,"",'xyz,123)

scala> val bad2 = ("abc", 123)
bad2: (String, Int) = (abc,123)

scala> new MyClass(good2)
res0: MyClass[(MustBeFirst, String)] = MyClass@5297aa76

scala> new MyClass(good3)
res1: MyClass[(MustBeFirst, String, Int)] = MyClass@3f501844

scala> new MyClass(good4)
res2: MyClass[(MustBeFirst, String, Symbol, Int)] = MyClass@24e15478

scala> new MyClass(bad2)
<console>:15: error: could not find implicit value for parameter ev: shapeless.ops.tuple.IsComposite[(String, Int)]{type H = MustBeFirst}
       new MyClass(bad2)
       ^

If you need to use a trait, you can put the ev (for "evidence") requirement inside the definition instead of in the constructor:

trait MyTrait[P <: Product] {
  implicit def ev: IsComposite[P] { type H = MustBeFirst }
}

Now any class instantiating MyTrait will have to provide evidence that P is a tuple with MustBeFirst as its first element.

Scala trait that accepts generic n-size tuple and returns m-sized , I'm currently developing a spark application that involves a series of complex joins between tuples, building out a N sized tuple based on the target data set. In Scala, a tuple is a value that contains a fixed number of elements, each with a distinct type.

Scala can't use generic tuple with unknown size because Products don's inherit themeselfs. You can try to use Shapeless or Products from play json lib.

Scala: How to define a generic method parameter that must extend a , An example. As a concrete example of how this works, start with a simple base type, such as this Scala trait : trait  A Scala tuple is a class that can contain a miscellaneous collection of elements. I like to think of them as a little bag or container you can use to hold things and pass them around. You create a tuple with the following syntax, enclosing its elements in parentheses. Here’s a tuple that contains an Int and a String: val stuff = (42, "fish

You need to inherit your trait from Product, through which you can have productIterator, productArity and, productElement to handle the returned value. Here is an example

case class MyClass()

trait MyTrait[T <: Product] {
  def getMyClass(x: T): Option[MyClass] = 
                if(
                     x.productIterator.hasNext 
                                   && 
                     x.productIterator.next().isInstanceOf[MyClass]
                 ){
    Some(x.productIterator.next().asInstanceOf[MyClass])
  } else {
    None
  }
}

case class Test() extends MyTrait[Product]

And you can invoke like this

Test().getMyClass((MyClass(), 1,3,4,5))
//res1: Option[MyClass] = Some(MyClass())

Test().getMyClass((1,3,4,5))
//res2: Option[MyClass] = None

Hope this helps you.

Convert (small enough) case classes to and from tuples using , Convert (small enough) case classes to and from tuples using shapeless tuplegeneric.scala. import shapeless._. import ops.hlist.Tupler. trait TupleGeneric​[C  I am hoping to write a Scala method which takes in a tuple of any size and type along with an index, and returns the element in the tuple at that index. I know how to do everything but preserve the type. I haven't yet figured out a way to make the return value be of the dynamic type of the tuple item. Here is the function I have so far:

If you are looking for compile time guarantee then this is one of the use cases for Shapeless,

You need to add Shapeless in your build.sbt,

libraryDependencies ++= Seq("
  com.chuusai" %% "shapeless" % "2.3.3"
)

Now, you can use Shapeless to define a typesafe getter which comes with compile time guarantees,

scala> import shapeless._
// import shapeless._

scala> import ops.tuple.IsComposite
// import ops.tuple.IsComposite

scala> import syntax.std.tuple._
// import syntax.std.tuple._

scala> case class Omg(omg: String)
// defined class Omg

scala> val myStringTuple = ("All is well", 42, "hope")
// myStringTuple: (String, Int, String) = (All is well,42,hope)

scala> val myOmgTuple = (Omg("All is well"), 42, "hope")
// myOmgTuple: (Omg, Int, String) = (Omg(All is well),42,hope)

Now if you want to enrich your tuples with a "first" getter with a specific type then,

scala> implicit class GetterForProduct[B <: Product](b: B) {
     |   def getFirst[A](implicit comp: IsComposite[B] { type H = A }): A = b.head
     | }
// defined class GetterForProduct

scala> val myString = myStringTuple.getFirst[String]
// myString: String = All is well

scala>   val myOmgError = myOmgTuple.getFirst[String]
// <console>:24: error: could not find implicit value for parameter comp: shapeless.ops.tuple.IsComposite[(Omg, Int, String)]{type H = String}
//         val myOmgError = myOmgTuple.getFirst[String]
//                                             ^

scala>   val myOmg = myOmgTuple.getFirst[Omg]
// myOmg: Omg = Omg(All is well

If you don't need the implicit enrichment and are just looking for a way to "lock" the type in a getter and use it for corresponding types,

scala> trait FirstGetterInProduct[A] {
     |   def getFirst[B <: Product](b: B)(implicit comp: IsComposite[B] { type H = A }): A = b.head
     | }
// defined trait FirstGetterInProduct

scala> object firstGetterInProductForString extends FirstGetterInProduct[String]
// defined object firstGetterInProductForString

scala> object firstGetterInProductForOmg extends FirstGetterInProduct[Omg]
// defined object firstGetterInProductForOmg

// Right tuple with right getter,
scala> val myString = firstGetterInProductForString.getFirst(myStringTuple)
// myString: String = All is well

// will fail at compile time for tuple with different type for first
scala> val myOmgError = firstGetterInProductForString.getFirst(myOmgTuple)
// <console>:23: error: could not find implicit value for parameter comp: shapeless.ops.tuple.IsComposite[(Omg, Int, String)]{type H = String}
//          val myOmgError = firstGetterInProductForString.getFirst(myOmgTuple)
//                                                                 ^

scala> val myOmg = firstGetterInProductForOmg.getFirst(myOmgTuple)
// myOmg: Omg = Omg(All is well)

Scala, generic tuple, Scala, generic tuple. scala list to tuple scala shapeless scala append to tuple scala tuple to case class scala tuple as parameter scala tuple type scala array to​  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more . How do I make a Generic Tuple dataset in Spark. Ask Question Asked 2 years, 3 months ago. Active 2 years, 3 months ago. Viewed 1k ti

10. Advanced Typing - Learning Scala [Book], One interesting feature is how the apparently high-level tuples and function scala> object ImplicitClasses { | implicit class Hello(s: String) { def hello Abstract types are an alternative to type parameters when designing generic classes. >> Is there any way in Scala's type system to make a func that takes an >> n-tuple and a m-tuple and returns a (n+m)-tuple? > > Yes, it's possible using a more generic model of a tuple, i.e. a list of > heterogeneously typed elements (sometimes called HList). MetaScala > contains an implementation of it:

Shapeless, Shapeless Is A Type Class And Dependent Type Based Generic Programming Library For Scala. Generic classes take a type as a parameter within square brackets []. One convention is to use the letter A as type parameter identifier, though any parameter name may be used. class Stack [ A ] { private var elements : List [ A ] = Nil def push ( x : A ) { elements = x :: elements } def peek : A = elements . head def pop () : A = { val currentTop = peek elements = elements . tail currentTop } }

The Type Astronaut's Guide to Shapeless - Books, For example, the Scala standard library provides generic products in the form of Tuples and a generic coproduct in the form of Either . We could have chosen 

Comments
  • This is compound type or "structural type" which, unlike "Duck typing", has a clearly-defined meaning is Scala.
  • This was surprisingly simple.
  • Just to strength constrain you may use Product { def _1: MyClass }, but it steel can accept case class with def _1
  • This is very simple to use, thank you. Anyway I had to enable reflective call, am I right?
  • It seems that with structural type the method _1 is called via reflection and this leads to poor performance.
  • Probably nitpicking, but I if read shapeless source correctly, IsComposite will also witness that the tuple is of size at least 2. It may be a relevant detail for the asker since tuples of size 1, however awkward, are a thing ^^
  • @C4stor IsComposite works for Tuple1, with tail type being Unit.
  • Altought I like this solution and shapeless in general, I don't know how to use this in my case. This is my actual use case: pastebin.com/yCKs0eiQ
  • Can you clarify what "don't inherit themselves" means here? I don't see what that means or how it would help.
  • Hi :-) The asker didn't specify unknown size but rather any size, which is weaker. For example, shapeless HLists (as you relevantly suggest) are definitely not of unknown size since their size is known at compile time :-) As Travis Brown, I can't quite figure what you mean in this answer, clarifying would be very helpful :-)
  • What is the "compile time guarantee" here? The OP has requested that tuples of any length, but only with the 1st element of a specific type, be accepted. (Not my down-vote.)