jamborta jamborta - 3 years ago 158
Scala Question

Shapeless record: update a field with different type

Is it possible to update an HList record with a different type, since given a list:

val l1 = 'field1 ->> 1 :: 'field2 ->> 2 :: HNil


updating
field2
with a different type would not update but add a new field:

l1 + ('field2 ->> "2")
//1 :: 2 :: "2" :: HNil


Is it possible to disable this behaviour?

Answer Source

You can do it by importing record ops and then use updateWith:

import shapeless.record._

l1.updateWith('field2)(_ => "2")

The function of the second section of updateWith is, roughly speaking, of type A => B, where A is the original type "pointed" by 'field2 and B is the type you want to transform it to. So, since the original value for 'field2 was 2, you could have done the transformation this way as well:

l1.updateWith('field2)(_.toString)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download