title: How to modify an arbitrary case class (e.g., replace the first field) using its generic representation in Shapeless?
body: <p>I am trying to write a function that given an arbitrary case class replaces the value of the first field with the given new value, using Shapeless.</p>
  
  <p>So far I have the following:</p>
  
  <pre><code>  def replaceHead[T, H, R &gt;: H :: HList](obj: T, newHead: H)(implicit generic: Generic.Aux[T, R]): T =
      generic.to(obj) match {
        case h :: t =&gt; generic.from(newHead :: t)
      }
  </code></pre>
  
  <p>If I don't put any type restrictions on <code>R</code>, I cannot use <code>generic.from(newHead :: t)</code> because it understandably expects a subtype of <code>R</code>. If I put <code>R &gt;: H :: HList</code>, I get the following error:</p>
  
  <pre><code>Error:(19, 22) could not find implicit value for parameter generic: shapeless.Generic.Aux[Test.Record,String :: shapeless.HList]
    println(replaceHead(Record("abc", 123), "def"))
  </code></pre>
  
  <p>The only way that I could get it to "work" is with an ugly hack like this that is not type safe:</p>
  
  <pre><code>  def replaceHead[T, H, R](obj: T, newHead: H)(implicit generic: Generic.Aux[T, R]): T =
      generic.to(obj) match {
        case h :: t =&gt; generic.from((newHead :: t).asInstanceOf[R])
      }
  
    replaceHead(Record("abc", 123), "def") // Works
    replaceHead(Record("abc", 123), 456) // Crashes at runtime
  </code></pre>
  
  <p>I understand that the root problem is because <code>R</code> ends up being for instance <code>String :: Int :: HNil</code> which <em>is</em> <code>String :: HList</code> but <code>String :: HList</code> is not necessarily <code>String :: Int :: HNil</code>, but I can't find a way to access the head of the generic representation without erasing the type signature of the tail.</p>