title: Kotlin: filterNotNull for values in a Map<K,V?>
body: <p>Here's the Kotlin code I'd like to write (with extra type annotations for clarity):</p>
  
  <pre><code>fun test(alpha: String, beta: String, gamma: String? = null, delta: String? = null) {
      val r1: Map&lt;String, String?&gt; =
          hashMapOf(
              "alpha" to alpha,
              "beta" to beta,
              "gamma" to gamma,
              "delta" to delta
          )
      val r2: Map&lt;String, String&gt; = r1.filterValues { it != null }
      callSomeFunction(r2)  // expects a parameter of type Map&lt;String, String&gt;
  }
  </code></pre>
  
  <p>Unfortunately, <code>r1.filterValues { it != null }</code> gives me back a <code>Map&lt;String, String?&gt;</code>, not a <code>Map&lt;String, String&gt;</code>.  I understand why this is; it's the same reason that <code>listOf(1, null).filter { it != null }</code> has a different type from <code>listOf(1, null).filterNotNull()</code>.  However, I still need to solve my problem!</p>
  
  <p>Is there an idiomatic way to "filterValuesNotNull" from a <code>Map</code>?</p>
  
  <p>Or, stepping up a level, is there some other idiomatic way to say "give me a <code>Map</code> of the following arguments, but skip those whose values are null"? I could resort to <a href="https://pl.kotl.in/DSomTAZSR" rel="nofollow noreferrer">this</a>, but I don't want to:</p>
  
  <pre><code>fun test(alpha: String, beta: String, gamma: String? = null, delta: String? = null) {
      var r1: MutableMap&lt;String, String&gt; = mutableMapOf(
          "alpha" to alpha,
          "beta" to beta
      )
      if (gamma != null) {
          r1["gamma"] = gamma
      }
      if (delta != null) {
          r1["delta"] = delta
      }
      callSomeFunction(r1)  // expects a parameter of type Map&lt;String, String&gt;
  }
  </code></pre>