title: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
body: <pre><code>fun checkLengthA(str : String?): Int = if (str.isNullOrBlank()) 0 else str.length
  </code></pre>
  
  <p><em>"Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?</em></p>
  
  <p>all null objects (or empty) are caught by isNullOrBlank(), so the str object in str.length can never be null (or empty). This can be achieved by replacing extension function with an explicit check.</p>
  
  <pre><code>fun checkLengthB(str : String?): Int = if (str == null) 0 else str.length
  </code></pre>
  
  <p>or less verbose expression:</p>
  
  <pre><code>fun checkLengthC(str : String?): Int = str?.length ?: 0
  </code></pre>
  
  <p>Both checkLengthB and checkLengthC will run without problems.</p>
  
  <p>Let's remove the nullable type from checkLengthA to avoid the compile error, highlighted above:</p>
  
  <pre><code>fun checkLengthA(str : String): Int = if (str.isNullOrBlank()) 0 else str.length
  </code></pre>
  
  <p>Now, we are only allowed to pars use non-null parameter of type String, so if we expect some null types then we have to put the "?" back.</p>
  
  <p>Looks like the complier does not understand that str of type String will never evaluate to null when running str.length and an extension function, but it will compile without problems if we use (str == null) in the if-else statement.</p>
  
  <p>Can anyone explain why it is happening?</p>