How to Get the ASCII Value of Character in Kotlin


The challenge

Get the ASCII value of a character.

The solution in Kotlin

Option 1:

val getAscii = Char::toInt

Option 2:

fun getAscii(c: Char) = c.code

Option 3:

fun getAscii(c: Char): Int {
    return c.code.toByte().toInt()
}

Test cases to validate our solution

import kotlin.test.assertEquals
import org.junit.Test

class TestExample {
  @Test
  fun `Basic tests`() {
    assertEquals(65, getAscii('A'))
    assertEquals(32, getAscii(' '))
    assertEquals(33, getAscii('!'))
  }
}