Scala, generic tuple











up vote
6
down vote

favorite












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










share|improve this question


























    up vote
    6
    down vote

    favorite












    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










    share|improve this question
























      up vote
      6
      down vote

      favorite









      up vote
      6
      down vote

      favorite











      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










      share|improve this question













      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







      scala generics






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 2 hours ago









      Gigitsu

      14311




      14311
























          6 Answers
          6






          active

          oldest

          votes

















          up vote
          2
          down vote













          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.






          share|improve this answer








          New contributor




          Ivan Aristov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.


















          • Can you clarify what "don't inherit themselves" means here? I don't see what that means or how it would help.
            – Travis Brown
            57 mins ago










          • 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 :-)
            – C4stor
            36 mins ago


















          up vote
          2
          down vote













          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 })


          And then:



          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.






          share|improve this answer





















          • 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
            39 mins ago










          • @C4stor Good point—I'll update the answer to clarify asap.
            – Travis Brown
            6 mins ago


















          up vote
          0
          down vote













          Because tuples of differing sizes are (almost) unrelated types, if you need the compiler to type-check the calls to getMyClass() then you might have to overload it.



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





          share|improve this answer




























            up vote
            0
            down vote













            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.






            share|improve this answer






























              up vote
              0
              down vote













              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
              }





              share|improve this answer



















              • 1




                This is compound type or "structural type" which, unlike "Duck typing", has a clearly-defined meaning is Scala.
                – Tim
                1 hour ago












              • @Tim, yes thank you I mean structural type.
                – mkUltra
                55 mins ago


















              up vote
              0
              down vote













              As others said you can use shapeless:



              import shapeless.ops.tuple.IsComposite
              import shapeless.syntax.std.tuple._

              class MyClass(i : Int){
              def hello() = println(i)
              }


              object Tup extends App {

              def getMyClass[P <: Product](p: P)(implicit ev: IsComposite[P]): MyClass = {
              if (p.head.isInstanceOf[MyClass]) p.head.asInstanceOf[MyClass] else throw new Exception()
              }
              val x= (new MyClass(1),5,6)
              val y = (new MyClass(2),7)

              val c = getMyClass(x)
              val c1 = getMyClass(y)
              c.hello()
              c1.hello()

              val c2 = getMyClass((1,5,6,7)) // exception
              c2.hello()

              }





              share|improve this answer





















                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53739656%2fscala-generic-tuple%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                6 Answers
                6






                active

                oldest

                votes








                6 Answers
                6






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                2
                down vote













                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.






                share|improve this answer








                New contributor




                Ivan Aristov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.


















                • Can you clarify what "don't inherit themselves" means here? I don't see what that means or how it would help.
                  – Travis Brown
                  57 mins ago










                • 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 :-)
                  – C4stor
                  36 mins ago















                up vote
                2
                down vote













                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.






                share|improve this answer








                New contributor




                Ivan Aristov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.


















                • Can you clarify what "don't inherit themselves" means here? I don't see what that means or how it would help.
                  – Travis Brown
                  57 mins ago










                • 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 :-)
                  – C4stor
                  36 mins ago













                up vote
                2
                down vote










                up vote
                2
                down vote









                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.






                share|improve this answer








                New contributor




                Ivan Aristov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                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.







                share|improve this answer








                New contributor




                Ivan Aristov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                share|improve this answer



                share|improve this answer






                New contributor




                Ivan Aristov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                answered 1 hour ago









                Ivan Aristov

                722




                722




                New contributor




                Ivan Aristov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                New contributor





                Ivan Aristov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                Ivan Aristov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.












                • Can you clarify what "don't inherit themselves" means here? I don't see what that means or how it would help.
                  – Travis Brown
                  57 mins ago










                • 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 :-)
                  – C4stor
                  36 mins ago


















                • Can you clarify what "don't inherit themselves" means here? I don't see what that means or how it would help.
                  – Travis Brown
                  57 mins ago










                • 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 :-)
                  – C4stor
                  36 mins ago
















                Can you clarify what "don't inherit themselves" means here? I don't see what that means or how it would help.
                – Travis Brown
                57 mins ago




                Can you clarify what "don't inherit themselves" means here? I don't see what that means or how it would help.
                – Travis Brown
                57 mins ago












                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 :-)
                – C4stor
                36 mins ago




                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 :-)
                – C4stor
                36 mins ago












                up vote
                2
                down vote













                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 })


                And then:



                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.






                share|improve this answer





















                • 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
                  39 mins ago










                • @C4stor Good point—I'll update the answer to clarify asap.
                  – Travis Brown
                  6 mins ago















                up vote
                2
                down vote













                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 })


                And then:



                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.






                share|improve this answer





















                • 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
                  39 mins ago










                • @C4stor Good point—I'll update the answer to clarify asap.
                  – Travis Brown
                  6 mins ago













                up vote
                2
                down vote










                up vote
                2
                down vote









                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 })


                And then:



                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.






                share|improve this answer












                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 })


                And then:



                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.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 1 hour ago









                Travis Brown

                112k9283528




                112k9283528












                • 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
                  39 mins ago










                • @C4stor Good point—I'll update the answer to clarify asap.
                  – Travis Brown
                  6 mins ago


















                • 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
                  39 mins ago










                • @C4stor Good point—I'll update the answer to clarify asap.
                  – Travis Brown
                  6 mins ago
















                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
                39 mins ago




                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
                39 mins ago












                @C4stor Good point—I'll update the answer to clarify asap.
                – Travis Brown
                6 mins ago




                @C4stor Good point—I'll update the answer to clarify asap.
                – Travis Brown
                6 mins ago










                up vote
                0
                down vote













                Because tuples of differing sizes are (almost) unrelated types, if you need the compiler to type-check the calls to getMyClass() then you might have to overload it.



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





                share|improve this answer

























                  up vote
                  0
                  down vote













                  Because tuples of differing sizes are (almost) unrelated types, if you need the compiler to type-check the calls to getMyClass() then you might have to overload it.



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





                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    Because tuples of differing sizes are (almost) unrelated types, if you need the compiler to type-check the calls to getMyClass() then you might have to overload it.



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





                    share|improve this answer












                    Because tuples of differing sizes are (almost) unrelated types, if you need the compiler to type-check the calls to getMyClass() then you might have to overload it.



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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 1 hour ago









                    jwvh

                    25k52038




                    25k52038






















                        up vote
                        0
                        down vote













                        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.






                        share|improve this answer



























                          up vote
                          0
                          down vote













                          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.






                          share|improve this answer

























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            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.






                            share|improve this answer














                            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.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited 1 hour ago

























                            answered 1 hour ago









                            Puneeth Reddy V

                            829715




                            829715






















                                up vote
                                0
                                down vote













                                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
                                }





                                share|improve this answer



















                                • 1




                                  This is compound type or "structural type" which, unlike "Duck typing", has a clearly-defined meaning is Scala.
                                  – Tim
                                  1 hour ago












                                • @Tim, yes thank you I mean structural type.
                                  – mkUltra
                                  55 mins ago















                                up vote
                                0
                                down vote













                                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
                                }





                                share|improve this answer



















                                • 1




                                  This is compound type or "structural type" which, unlike "Duck typing", has a clearly-defined meaning is Scala.
                                  – Tim
                                  1 hour ago












                                • @Tim, yes thank you I mean structural type.
                                  – mkUltra
                                  55 mins ago













                                up vote
                                0
                                down vote










                                up vote
                                0
                                down vote









                                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
                                }





                                share|improve this answer














                                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
                                }






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited 54 mins ago

























                                answered 1 hour ago









                                mkUltra

                                533519




                                533519








                                • 1




                                  This is compound type or "structural type" which, unlike "Duck typing", has a clearly-defined meaning is Scala.
                                  – Tim
                                  1 hour ago












                                • @Tim, yes thank you I mean structural type.
                                  – mkUltra
                                  55 mins ago














                                • 1




                                  This is compound type or "structural type" which, unlike "Duck typing", has a clearly-defined meaning is Scala.
                                  – Tim
                                  1 hour ago












                                • @Tim, yes thank you I mean structural type.
                                  – mkUltra
                                  55 mins ago








                                1




                                1




                                This is compound type or "structural type" which, unlike "Duck typing", has a clearly-defined meaning is Scala.
                                – Tim
                                1 hour ago






                                This is compound type or "structural type" which, unlike "Duck typing", has a clearly-defined meaning is Scala.
                                – Tim
                                1 hour ago














                                @Tim, yes thank you I mean structural type.
                                – mkUltra
                                55 mins ago




                                @Tim, yes thank you I mean structural type.
                                – mkUltra
                                55 mins ago










                                up vote
                                0
                                down vote













                                As others said you can use shapeless:



                                import shapeless.ops.tuple.IsComposite
                                import shapeless.syntax.std.tuple._

                                class MyClass(i : Int){
                                def hello() = println(i)
                                }


                                object Tup extends App {

                                def getMyClass[P <: Product](p: P)(implicit ev: IsComposite[P]): MyClass = {
                                if (p.head.isInstanceOf[MyClass]) p.head.asInstanceOf[MyClass] else throw new Exception()
                                }
                                val x= (new MyClass(1),5,6)
                                val y = (new MyClass(2),7)

                                val c = getMyClass(x)
                                val c1 = getMyClass(y)
                                c.hello()
                                c1.hello()

                                val c2 = getMyClass((1,5,6,7)) // exception
                                c2.hello()

                                }





                                share|improve this answer

























                                  up vote
                                  0
                                  down vote













                                  As others said you can use shapeless:



                                  import shapeless.ops.tuple.IsComposite
                                  import shapeless.syntax.std.tuple._

                                  class MyClass(i : Int){
                                  def hello() = println(i)
                                  }


                                  object Tup extends App {

                                  def getMyClass[P <: Product](p: P)(implicit ev: IsComposite[P]): MyClass = {
                                  if (p.head.isInstanceOf[MyClass]) p.head.asInstanceOf[MyClass] else throw new Exception()
                                  }
                                  val x= (new MyClass(1),5,6)
                                  val y = (new MyClass(2),7)

                                  val c = getMyClass(x)
                                  val c1 = getMyClass(y)
                                  c.hello()
                                  c1.hello()

                                  val c2 = getMyClass((1,5,6,7)) // exception
                                  c2.hello()

                                  }





                                  share|improve this answer























                                    up vote
                                    0
                                    down vote










                                    up vote
                                    0
                                    down vote









                                    As others said you can use shapeless:



                                    import shapeless.ops.tuple.IsComposite
                                    import shapeless.syntax.std.tuple._

                                    class MyClass(i : Int){
                                    def hello() = println(i)
                                    }


                                    object Tup extends App {

                                    def getMyClass[P <: Product](p: P)(implicit ev: IsComposite[P]): MyClass = {
                                    if (p.head.isInstanceOf[MyClass]) p.head.asInstanceOf[MyClass] else throw new Exception()
                                    }
                                    val x= (new MyClass(1),5,6)
                                    val y = (new MyClass(2),7)

                                    val c = getMyClass(x)
                                    val c1 = getMyClass(y)
                                    c.hello()
                                    c1.hello()

                                    val c2 = getMyClass((1,5,6,7)) // exception
                                    c2.hello()

                                    }





                                    share|improve this answer












                                    As others said you can use shapeless:



                                    import shapeless.ops.tuple.IsComposite
                                    import shapeless.syntax.std.tuple._

                                    class MyClass(i : Int){
                                    def hello() = println(i)
                                    }


                                    object Tup extends App {

                                    def getMyClass[P <: Product](p: P)(implicit ev: IsComposite[P]): MyClass = {
                                    if (p.head.isInstanceOf[MyClass]) p.head.asInstanceOf[MyClass] else throw new Exception()
                                    }
                                    val x= (new MyClass(1),5,6)
                                    val y = (new MyClass(2),7)

                                    val c = getMyClass(x)
                                    val c1 = getMyClass(y)
                                    c.hello()
                                    c1.hello()

                                    val c2 = getMyClass((1,5,6,7)) // exception
                                    c2.hello()

                                    }






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered 32 mins ago









                                    Arnon Rotem-Gal-Oz

                                    18.6k13260




                                    18.6k13260






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53739656%2fscala-generic-tuple%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        What visual should I use to simply compare current year value vs last year in Power BI desktop

                                        Alexandru Averescu

                                        Trompette piccolo