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












0















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





























    0















    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



























      0












      0








      0








      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 '18 at 15:58









      Daniel Hinojosa

      85458




      85458










      asked Nov 22 '18 at 2:09









      Petro SemeniukPetro Semeniuk

      4,91533455




      4,91533455
























          2 Answers
          2






          active

          oldest

          votes


















          0














          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































            0














            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',
              autoActivateHeartbeat: false,
              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









              0














              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




























                0














                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


























                  0












                  0








                  0







                  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 '18 at 16:56









                  Daniel HinojosaDaniel Hinojosa

                  85458




                  85458

























                      0














                      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




























                        0














                        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


























                          0












                          0








                          0







                          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 '18 at 22:25









                          AlecAlec

                          24.6k44589




                          24.6k44589






























                              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.




                              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

                              MongoDB - Not Authorized To Execute Command

                              How to fix TextFormField cause rebuild widget in Flutter

                              in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith