How to get map of field names to field types of case class with shapeless











up vote
0
down vote

favorite












I browsed pretty much all tutorials and have "The Type Astronauts" on my desk but I still can't figure out how to write snippet which can extract map of names to types using shapeless from case class. To be precise I'm after following interface:



case class Sample(id: String, date: LocalDate)

def sampleExpectedMetadata = expectedMetadata[Sample] // = ("id" -> "String", "date" -> "LocalDate")

def expectedMetadata[T]: Map[String, String] = ???


Help from anyone who can assist with writing correct implementation would be greatly appreciated.










share|improve this question




























    up vote
    0
    down vote

    favorite












    I browsed pretty much all tutorials and have "The Type Astronauts" on my desk but I still can't figure out how to write snippet which can extract map of names to types using shapeless from case class. To be precise I'm after following interface:



    case class Sample(id: String, date: LocalDate)

    def sampleExpectedMetadata = expectedMetadata[Sample] // = ("id" -> "String", "date" -> "LocalDate")

    def expectedMetadata[T]: Map[String, String] = ???


    Help from anyone who can assist with writing correct implementation would be greatly appreciated.










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I browsed pretty much all tutorials and have "The Type Astronauts" on my desk but I still can't figure out how to write snippet which can extract map of names to types using shapeless from case class. To be precise I'm after following interface:



      case class Sample(id: String, date: LocalDate)

      def sampleExpectedMetadata = expectedMetadata[Sample] // = ("id" -> "String", "date" -> "LocalDate")

      def expectedMetadata[T]: Map[String, String] = ???


      Help from anyone who can assist with writing correct implementation would be greatly appreciated.










      share|improve this question















      I browsed pretty much all tutorials and have "The Type Astronauts" on my desk but I still can't figure out how to write snippet which can extract map of names to types using shapeless from case class. To be precise I'm after following interface:



      case class Sample(id: String, date: LocalDate)

      def sampleExpectedMetadata = expectedMetadata[Sample] // = ("id" -> "String", "date" -> "LocalDate")

      def expectedMetadata[T]: Map[String, String] = ???


      Help from anyone who can assist with writing correct implementation would be greatly appreciated.







      scala generic-programming shapeless






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 at 15:58









      Daniel Hinojosa

      83458




      83458










      asked Nov 22 at 2:09









      Petro Semeniuk

      4,82523454




      4,82523454
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote













          I could be wrong that Shapeless would have nothing to do with this sort of introspection, using the answer from Get field names list from case class and refining it, your answer would be:



          import scala.reflect.runtime.universe._

          def expectedMetadata[T](implicit t:TypeTag[T]):Map[String, String] =
          t.tpe.members
          .collect { case m:MethodSymbol if m.isCaseAccessor => m }
          .map(x => x.name.toString -> x.returnType.toString)
          .toMap


          Where, expectedMetadata[Sample] will return Map[String,String] = Map(date -> java.time.LocalDate, id -> String)






          share|improve this answer




























            up vote
            0
            down vote













            Did you have something like this in mind?



            import shapeless._
            import shapeless.record._
            import shapeless.labelled._

            object expectedMetadata {
            def apply[T](implicit g: GetFieldTypes[T]): Map[String, String] = g.getFieldTypes

            sealed trait GetFieldTypes[T] {
            def getFieldTypes: Map[String,String]
            }

            implicit val hnil = new GetFieldTypes[HNil] {
            def getFieldTypes = Map.empty
            }

            implicit def hcons[K <: Symbol, V, T <: HList](implicit
            wit: Witness.Aux[K],
            typ: Typeable[V],
            rest: GetFieldTypes[T]
            ) = new GetFieldTypes[FieldType[K, V] :: T] {
            def getFieldTypes = rest.getFieldTypes + (wit.value.name -> typ.describe)
            }

            implicit def caseClass[T, G](implicit
            lg: LabelledGeneric.Aux[T, G],
            rest: GetFieldTypes[G]
            ) = new GetFieldTypes[T] {
            def getFieldTypes = rest.getFieldTypes
            }
            }


            Sample use:



            scala> case class Sample(id: String, date: LocalDate)
            scala> expectedMetadata[Sample]
            res1: Map[String,String] = Map(date -> LocalDate, id -> String)





            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%2f53422945%2fhow-to-get-map-of-field-names-to-field-types-of-case-class-with-shapeless%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              0
              down vote













              I could be wrong that Shapeless would have nothing to do with this sort of introspection, using the answer from Get field names list from case class and refining it, your answer would be:



              import scala.reflect.runtime.universe._

              def expectedMetadata[T](implicit t:TypeTag[T]):Map[String, String] =
              t.tpe.members
              .collect { case m:MethodSymbol if m.isCaseAccessor => m }
              .map(x => x.name.toString -> x.returnType.toString)
              .toMap


              Where, expectedMetadata[Sample] will return Map[String,String] = Map(date -> java.time.LocalDate, id -> String)






              share|improve this answer

























                up vote
                0
                down vote













                I could be wrong that Shapeless would have nothing to do with this sort of introspection, using the answer from Get field names list from case class and refining it, your answer would be:



                import scala.reflect.runtime.universe._

                def expectedMetadata[T](implicit t:TypeTag[T]):Map[String, String] =
                t.tpe.members
                .collect { case m:MethodSymbol if m.isCaseAccessor => m }
                .map(x => x.name.toString -> x.returnType.toString)
                .toMap


                Where, expectedMetadata[Sample] will return Map[String,String] = Map(date -> java.time.LocalDate, id -> String)






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  I could be wrong that Shapeless would have nothing to do with this sort of introspection, using the answer from Get field names list from case class and refining it, your answer would be:



                  import scala.reflect.runtime.universe._

                  def expectedMetadata[T](implicit t:TypeTag[T]):Map[String, String] =
                  t.tpe.members
                  .collect { case m:MethodSymbol if m.isCaseAccessor => m }
                  .map(x => x.name.toString -> x.returnType.toString)
                  .toMap


                  Where, expectedMetadata[Sample] will return Map[String,String] = Map(date -> java.time.LocalDate, id -> String)






                  share|improve this answer












                  I could be wrong that Shapeless would have nothing to do with this sort of introspection, using the answer from Get field names list from case class and refining it, your answer would be:



                  import scala.reflect.runtime.universe._

                  def expectedMetadata[T](implicit t:TypeTag[T]):Map[String, String] =
                  t.tpe.members
                  .collect { case m:MethodSymbol if m.isCaseAccessor => m }
                  .map(x => x.name.toString -> x.returnType.toString)
                  .toMap


                  Where, expectedMetadata[Sample] will return Map[String,String] = Map(date -> java.time.LocalDate, id -> String)







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 22 at 16:56









                  Daniel Hinojosa

                  83458




                  83458
























                      up vote
                      0
                      down vote













                      Did you have something like this in mind?



                      import shapeless._
                      import shapeless.record._
                      import shapeless.labelled._

                      object expectedMetadata {
                      def apply[T](implicit g: GetFieldTypes[T]): Map[String, String] = g.getFieldTypes

                      sealed trait GetFieldTypes[T] {
                      def getFieldTypes: Map[String,String]
                      }

                      implicit val hnil = new GetFieldTypes[HNil] {
                      def getFieldTypes = Map.empty
                      }

                      implicit def hcons[K <: Symbol, V, T <: HList](implicit
                      wit: Witness.Aux[K],
                      typ: Typeable[V],
                      rest: GetFieldTypes[T]
                      ) = new GetFieldTypes[FieldType[K, V] :: T] {
                      def getFieldTypes = rest.getFieldTypes + (wit.value.name -> typ.describe)
                      }

                      implicit def caseClass[T, G](implicit
                      lg: LabelledGeneric.Aux[T, G],
                      rest: GetFieldTypes[G]
                      ) = new GetFieldTypes[T] {
                      def getFieldTypes = rest.getFieldTypes
                      }
                      }


                      Sample use:



                      scala> case class Sample(id: String, date: LocalDate)
                      scala> expectedMetadata[Sample]
                      res1: Map[String,String] = Map(date -> LocalDate, id -> String)





                      share|improve this answer

























                        up vote
                        0
                        down vote













                        Did you have something like this in mind?



                        import shapeless._
                        import shapeless.record._
                        import shapeless.labelled._

                        object expectedMetadata {
                        def apply[T](implicit g: GetFieldTypes[T]): Map[String, String] = g.getFieldTypes

                        sealed trait GetFieldTypes[T] {
                        def getFieldTypes: Map[String,String]
                        }

                        implicit val hnil = new GetFieldTypes[HNil] {
                        def getFieldTypes = Map.empty
                        }

                        implicit def hcons[K <: Symbol, V, T <: HList](implicit
                        wit: Witness.Aux[K],
                        typ: Typeable[V],
                        rest: GetFieldTypes[T]
                        ) = new GetFieldTypes[FieldType[K, V] :: T] {
                        def getFieldTypes = rest.getFieldTypes + (wit.value.name -> typ.describe)
                        }

                        implicit def caseClass[T, G](implicit
                        lg: LabelledGeneric.Aux[T, G],
                        rest: GetFieldTypes[G]
                        ) = new GetFieldTypes[T] {
                        def getFieldTypes = rest.getFieldTypes
                        }
                        }


                        Sample use:



                        scala> case class Sample(id: String, date: LocalDate)
                        scala> expectedMetadata[Sample]
                        res1: Map[String,String] = Map(date -> LocalDate, id -> String)





                        share|improve this answer























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          Did you have something like this in mind?



                          import shapeless._
                          import shapeless.record._
                          import shapeless.labelled._

                          object expectedMetadata {
                          def apply[T](implicit g: GetFieldTypes[T]): Map[String, String] = g.getFieldTypes

                          sealed trait GetFieldTypes[T] {
                          def getFieldTypes: Map[String,String]
                          }

                          implicit val hnil = new GetFieldTypes[HNil] {
                          def getFieldTypes = Map.empty
                          }

                          implicit def hcons[K <: Symbol, V, T <: HList](implicit
                          wit: Witness.Aux[K],
                          typ: Typeable[V],
                          rest: GetFieldTypes[T]
                          ) = new GetFieldTypes[FieldType[K, V] :: T] {
                          def getFieldTypes = rest.getFieldTypes + (wit.value.name -> typ.describe)
                          }

                          implicit def caseClass[T, G](implicit
                          lg: LabelledGeneric.Aux[T, G],
                          rest: GetFieldTypes[G]
                          ) = new GetFieldTypes[T] {
                          def getFieldTypes = rest.getFieldTypes
                          }
                          }


                          Sample use:



                          scala> case class Sample(id: String, date: LocalDate)
                          scala> expectedMetadata[Sample]
                          res1: Map[String,String] = Map(date -> LocalDate, id -> String)





                          share|improve this answer












                          Did you have something like this in mind?



                          import shapeless._
                          import shapeless.record._
                          import shapeless.labelled._

                          object expectedMetadata {
                          def apply[T](implicit g: GetFieldTypes[T]): Map[String, String] = g.getFieldTypes

                          sealed trait GetFieldTypes[T] {
                          def getFieldTypes: Map[String,String]
                          }

                          implicit val hnil = new GetFieldTypes[HNil] {
                          def getFieldTypes = Map.empty
                          }

                          implicit def hcons[K <: Symbol, V, T <: HList](implicit
                          wit: Witness.Aux[K],
                          typ: Typeable[V],
                          rest: GetFieldTypes[T]
                          ) = new GetFieldTypes[FieldType[K, V] :: T] {
                          def getFieldTypes = rest.getFieldTypes + (wit.value.name -> typ.describe)
                          }

                          implicit def caseClass[T, G](implicit
                          lg: LabelledGeneric.Aux[T, G],
                          rest: GetFieldTypes[G]
                          ) = new GetFieldTypes[T] {
                          def getFieldTypes = rest.getFieldTypes
                          }
                          }


                          Sample use:



                          scala> case class Sample(id: String, date: LocalDate)
                          scala> expectedMetadata[Sample]
                          res1: Map[String,String] = Map(date -> LocalDate, id -> String)






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 22 at 22:25









                          Alec

                          24k44487




                          24k44487






























                              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%2f53422945%2fhow-to-get-map-of-field-names-to-field-types-of-case-class-with-shapeless%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

                              A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                              Calculate evaluation metrics using cross_val_predict sklearn

                              Insert data from modal to MySQL (multiple modal on website)