title: How to trim an option string in a Slick column mapping when using Play Scala
body: <p>What is the correct way, and where is the correct place, to trim a value from a fixed character database column when using the Play framework with Slick?</p>
  
  <p>The reason I want to trim the string is that the database schema specifies a <code>character(40)</code> column type rather than a <code>character varying</code> type.</p>
  
  <p>I have this case class:</p>
  
  <pre><code>case class Test(id: Long, trimMe: Option[String])
  </code></pre>
  
  <p>I have this Slick table relation:</p>
  
  <pre><code>class Tests(tag: Tag) extends Table[Test](tag, "test") {
  
    def id     = column[Long  ]("test_id", O.PrimaryKey, O.AutoInc)
    def trimMe = column[String]("trim_me"                         )
  
    def * = (id, trimMe) &lt;&gt; (Test.tupled, Test.unapply _)
  
  }
  </code></pre>
  
  <p>I have this test class with a JSON mapping:</p>
  
  <pre><code>object TrimTest {
  
    implicit val testWrite = new Writes[Test] {
      def writes(test: Test) = Json.obj(
        "id"   -&gt; test.id    ,
        "trim" -&gt; test.trimMe
      )}
  }
  </code></pre>
  
  <p>This all works but returns a space-padded string.</p>
  
  <p>I tried a few variations of trimming in the JSON mapper:</p>
  
  <pre><code>object TrimTest {
  
    implicit val testWrite = new Writes[Test] {
      def writes(test: Test) = Json.obj(
        "id"    -&gt; test.id                              ,
        "trim1" -&gt; test.trimMe.map(_.trim)              ,
        "trim2" -&gt; test.trimMe.fold("") {_.trim}        ,
        "trim3" -&gt; test.trimMe.map(_.trim).getOrElse("")
      )}
  }
  </code></pre>
  
  <p><code>trim1</code> above works, but returns <code>null</code> when the optional value is not present.</p>
  
  <p><code>trim2</code> does work for all cases, but I have seen it stated in various places that <code>map</code> then <code>getForElse</code> is "more idiomatic Scala" than using <code>fold</code>.</p>
  
  <p><code>trim3</code> is just past the limit of my current understanding of Scala and shows my intent but does not compile.</p>
  
  <p>The compilation error in the case of <code>trim3</code> is:</p>
  
  <blockquote>
    <p>type mismatch;
    found   : Object
    required: play.api.libs.json.Json.JsValueWrapper</p>
  </blockquote>
  
  <p>I can certainly live with using <code>fold</code>, but what is the usual way to do this?</p>