Kotlin tutorial : Character in kotlin and functions of Character class

Character in kotlin :

In Kotlin, we use “Char” to represent a character. Also, we can create one character variable by using one single quote pair. For example, for the following program :

fun main(args: Array) {
    val letter = 'c'
    println("Current value of 'letter' is " + letter)

    if(letter is Char){
        println("It is a character")
    }else{
        println("It is not character")
    }
}

It will print :

Current value of 'letter' is c
It is a character

So, even though we are not defining it as a character like var letter : Char = ‘c’, it is defined as “character”.

Escaped characters in Kotlin :

Escaped characters are special characters like new line , tab etc.These are escaped using one backslash. In kotlin, the supported escaped characters are : \t, \b, \n, \r, ’, ”, \ and $.

Few important functions of Char class :

  1. fun toByte(): Byte : It returns the value of the character as byte.
  2. fun toChar(): Char : Returns the value of the character as ‘Char’.
  3. fun toDouble(): Double : Returns the value of the character as ‘Double’.
  4. fun toFloat(): Float : Returns the value of the character as ‘Float’.
  5. fun toInt(): Int : Returns the value of the character as ‘Int’.
  6. fun toLong(): Long : Returns the value of the character as ‘Long’.
  7. fun toShort(): Short : Returns the value of the character as ‘Short
  8. equals : Returns ‘true’ if the value of one character is equal to another.
  9. fun Char.isDigit(): Boolean : Returns true if the character is a digit
  10. fun Char.isLetter(): Boolean : Returns true if the character is a letter
  11. isLowerCase : Returns ‘true’ if the given character is lowercase.
  12. isUpperCase : Returns ‘true’ if the given character is uppercase.
  13. toLowerCase : Converts the character to lowercase.
  14. toUpperCase : Converts the character to uppercase.