title: How to make this kotlin script do checks with errors, but return a value in an idiomatic way?
body: <p>I wrote this function here to fetch an API key required during our gradle build:</p>
  <pre><code>fun getApiKey(): String {
      val keyFile = File(&quot;../whatever&quot;)
      if (!keyFile.exists()) {
          logger.error(&quot;whatever missing from parent directory&quot;)
      }
  
      val regex = &quot;ARTIFACTORY_APIKEY: (\\S+)&quot;.toRegex()
      var key:String?  = null
      keyFile.forEachLine {
          val matchResult = regex.find(it)
          if (matchResult != null) {
              key = matchResult.groupValues[1]
          }
      }
  
      if (key == null) {
          logger.error(&quot;whatever doesn't contain API KEY&quot;)
      }
  
      return key!!
  }
  </code></pre>
  <p>It gets the job done (gives meaningful error messages when my file is missing or has bad content), and returns the value otherwise. But well, it feels overly clumsy, I am sure there must be more elegant ways to express such functionality within a gradle file?</p>