score:2
Based on LabelledGeneric
and Keys
type classes
import shapeless.LabelledGeneric
import shapeless.HList
import shapeless.ops.hlist.ToTraversable
import shapeless.ops.record.Keys
case class Person(name: String, age: Int)
def fields[P <: Product, L <: HList, R <: HList](a: P)(
implicit
gen: LabelledGeneric.Aux[P, L],
keys: Keys.Aux[L, R],
ts: ToTraversable.Aux[R, List, Symbol]
): List[(String, String)] = {
val fieldNames = keys().toList.map(_.name)
val values = a.productIterator.toList.map(_.toString)
fieldNames zip values
}
fields(Person("Jean-Luc, Picard", 70))
// : List[(String, String)] = List((name,Jean-Luc, Picard), (age,70))
IDEA ... shows an error ... No implicit arguments
IntelliJ in-editor error highlighting is sometimes not 100% accurate when it comes to type-level code and macros. Best is to consider it as just guidance, and put trust in the Scala compiler proper, so if compiler is happy but IJ is not, then go with the compiler. Another options is to try Scala Metals which should have one-to-one mapping between compiler diagnostics and in-editor error highlighting.
why you used LabelledGeneric.Aux, Keys.Aux, ToTraversable.Aux
This is using a design pattern called type classes. My suggestion would be to work through The Type Astronaut's Guide to Shapeless in particular section on Chaining dependent functions
Dependently typed functions provide a means of calculating one type from another. We can chain dependently typed functions to perform calculations involving multiple steps.
Consider the following dependency between types
input type
|
gen: LabelledGeneric.Aux[P, L],
|
output type
input type
|
keys: Keys.Aux[L, R]
|
output type
Note how for example the output type L
of LabelledGeneric
becomes the input type of Keys
. In this way you are showing the compiler the relationship between the types and in return the compiler is able to give your an HList
representing the field names from Product
representing the particular case class, and all this before the program even runs.
ToTraversable
is needed so you can get back a regular Scala List
from an HList
which enables the following bit
.toList.map(_.name)
Hopefully this gives you at least a little bit of direction. Some keywords to search for are: type classes, dependent types, implicit resolution, type alias Aux pattern, type members vs type parameters, type refinement, etc. Typelevel community has a new Discord channel where you can get further direction.
Source: stackoverflow.com
Related Query
- How to get Scala case class fields and values as (String, String) with Shapeless or Macro
- How to get list of fields and subfields of a Scala case class
- How to split comma separated string and get n values in Spark Scala dataframe?
- Scala compare case class and get changed fields
- Get case class field's name and type with shapeless
- How to check if a String contains multiple values and ignore case with StringUtils
- How to convert between to case classes with `mostly the same` fields using Scala Shapeless
- How to get map of field names to field types of case class with shapeless
- How to define case class with a list of tuples and access the tuples in scala
- How can I extract values from a String to create a case class instance in Scala
- How to parse a csv with matching case class and store the output to treemap[Int, List[List[InputConfig]] object in scala
- Compare a list values with case class using Scala and Spark
- How to update a mongo record using Rogue with MongoCaseClassField when case class contains a scala Enumeration
- How to get around the Scala case class limit of 22 fields?
- Scala 2.10 reflection, how do I extract the field values from a case class, i.e. field list from case class
- Shapeless - turn a case class into another with fields in different order
- How to get logging working in scala unit tests with testng, slf4s, and logback
- How do I get Intellij IDEA 12.0 to work with Play Framework 2.1.0 app and Scala 2.10.0?
- How to create a Scala class with private field with public getter, and primary constructor taking a parameter of the same name
- How to shapeless case classes with attributes and typeclasses?
- Scala wont pattern match with java.lang.String and Case Class
- Scala spark: how to use dataset for a case class with the schema has snake_case?
- Problem with bounded type parameterised case class and default args in Scala
- How do I add a no-arg constructor to a Scala case class with a macro annotation?
- compare case class fields with sub fields of another case class in scala
- Trim values of String fields of a case class
- How can I write and read an empty case class with play-json?
- shapeless convert case class to HList and skip all option fields
- Scala case class copy constructor with dynamic fields
- Scala - case class with 100 fields (StackOverflowError)
More Query from same tag
- How to apply implicit conversions between tuples?
- Unable to build Scala Maven project
- Ignore JSON field Play Controller Scala
- Import code packaged as jar into another sbt project
- How to secure APIs in Scala
- What does the <- operator do in Scala
- How to use file from Databricks FileStore
- flattern scala array data type column to multiple columns
- gitlab ci: sbt recompiles in each stage
- How to create a Spark SQL Dataframe with list of Map objects
- Scala Function Chaining and handle failure
- How is the underscore different from a placeholder in a partially applied function in Scala?
- How to call an overloaded method from a generic type
- How to sum 2 joda-time DateTime values (one containing a date and a zero time and another containing a time and a zero date)?
- Need to read and then remove duplicates from multiple CSV file in Spark scala
- Scala: Best way to iterate over collection and populate Array
- Scala Spark Read from AWS S3 - com.amazonaws.SdkClientException: Unable to load credentials from service endpoint
- Why does Scala's Future.onComplete needs an ExecutionContext
- Extract data from mysql using Scala and spark
- Halting a Process[Task, O] on user input
- Wrong FS s3://ss-pprd-v2-dart//tempdir/962c6007-77c0-4294-b021-b9498e3d66ab/manifest.json -expected s3a://ss-pprd-v2-dart
- How can I pass a RDD from scala to python?
- When should I use Scala's Array instead of one of the other collections?
- How do I group items T from an iterator into an Iterator[Seq[T]]
- Spark UDAF with ArrayType as bufferSchema performance issues
- @specialized + inner classes not allowed in scala?
- Why does predicate not return a Boolean?
- Ignite, Spark - Deserializing the [B value from sql query result to HashMap
- Scala SBT custom lib managed path
- type-case in a type synonym