How to Get the ASCII Value of Character in Kotlin

0 min read 63 words

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('!'))
  }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags