2

I am trying to learn Shapeless. I have created a very simple case class:

case class Holding(ticker: String, assetClass: String, units: Double, mktValue: Double)

I would like to be able to group on any arbitrary field, i.e. ticker or assetClass on a list of Holdings and sum on units and mktValue.

This works:

val map = list.groupBy(lens[Holding] >> 'assetClass)

So, does this:

val mapped = Map( 'assetClass -> (lens[Holding] >> 'assetClass), 'ticker -> (lens[Holding] >> 'ticker))

def makeLens(sym: Symbol) = {
   mapped.get(sym).get
}

val map = list.groupBy(makeLens('assetClass).get)

Creating a map to hold the lenses does not seem to follow the spirit of the 'scrap your bolierplate' approach. Is there any way to do this:

val sym = 'assetClass
val map = list.groupBy(lens[Holding] >> sym)

I need to be able to define a method as generically as possible that takes an arbitrary symbol and groups the list. Is that possible?

nvalada
  • 265
  • 1
  • 11
  • Have you seen my answer [here](http://stackoverflow.com/a/26188482/334519)? – Travis Brown Oct 20 '14 at 00:01
  • Yes. But what if the Symbol to be used for the makeLens method is only really known at runtime. I would like to use this from Java and as a replacement for a Java library using QueryDSL - [link](http://www.querydsl.com/static/querydsl/latest/reference/html/ch02s08.html) – nvalada Oct 20 '14 at 00:57
  • Is the example [here](https://gist.github.com/milessabin/11244675#file-gistfile1-scala-L27) close enough? Note though that the symbol identifying the field must be statically known at the call site ... it can't be some arbitrary Symbol constructed from IO. – Miles Sabin Oct 20 '14 at 06:30
  • Ok. I was hoping it could be some arbitrary Symbol constructed from IO. – nvalada Oct 20 '14 at 11:31

0 Answers0