title: Dynamic property access in Kotlin
body: <p>From the Kotlin Fundamentals course, we have this code:</p>
  <pre class="lang-kotlin prettyprint-override"><code>@BindingAdapter(&quot;sleepImage&quot;)
  fun ImageView.setSleepImage(item: SleepNight?) {
      item?.let {
          setImageResource(when (item.sleepQuality) {
              0 -&gt; R.drawable.ic_sleep_0
              1 -&gt; R.drawable.ic_sleep_1
              2 -&gt; R.drawable.ic_sleep_2
              3 -&gt; R.drawable.ic_sleep_3
              4 -&gt; R.drawable.ic_sleep_4
              5 -&gt; R.drawable.ic_sleep_5
              else -&gt; R.drawable.ic_sleep_active
          })
      }
  }
  </code></pre>
  <p>In other languages I would simplify this by using the <code>sleepQuality</code> integer to look up the matching element, in Typescript for example:</p>
  <pre class="lang-js prettyprint-override"><code>setImageResource(R.drawable[`ic_sleep_${item.sleepQuality}`] ?? R.drawable.ic_sleep_active)
  </code></pre>
  <p>To start trying this out even my first step doesn't compile:</p>
  <pre><code>0 -&gt; R.drawable[&quot;ic_sleep_0&quot;] // doesn't compile
  </code></pre>
  <p>Is this kind of operation possible in Kotlin?</p>
  <h3>Edit/Update</h3>
  <p>There's a few good responses here.</p>
  <p>It looks like for this specific use case, I can look up resources by string, similar to what I'm trying:</p>
  <pre><code>val resId = context.resources.getIdentifier(&quot;ic_sleep_${item.sleepQuality}&quot;, &quot;drawable&quot;, context.packageName)
  </code></pre>
  <p>However, this is not a general solution. The following does not work:</p>
  <pre><code>val x = item['sleepQuality']
  </code></pre>
  <p>As noted in some responses, this may be possible using reflection. How would this be done?</p>