Home Kotlin giving an empty char literal error
Post
Cancel

Kotlin giving an empty char literal error

So the last couple of weeks I’ve been working out the advent of code of 2022 in Kotlin. The reason herefore can be found in the Advent of Code 2022 introduction.

When working on day three, I came accross a weird error message when trying to return an empty character from one of my methods. The return '' statement gave me this error message Empty Character Literal.

The solution

So after some Googling I came accross a Java thread on Stack Overflow, saying that in Java a character can not be empty just like other primitives (the Stackoverflow post).

So in Kotlin (and Java for that matter), the solution was as simple as returning a 0. But that was a bit strange for me, given that I want to return a char I don’t want to return some random magic number.

So I started digging into the documentation for the Char datatype on the Kotlin site where I found the static property Char.MIN_VALUE. Which according to the docs contains the ‘The minimum value of a character code unit.(Jetbrains, n.d.).

If we print this value, we get nothing as the output. Just as we expected. But looking into the documentation for the basic types of Java, the minimum value for a char literal is 0 (Oracle, n.d.). So when we’re converting the char to an integer, we get the expected 0 as an integer.

1
2
3
4
fun main() {
    println(Char.MIN_VALUE) // Prints nothing
    println(Char.MIN_VALUE.toInt()) // Prints 0
}
This post is licensed under CC BY 4.0 by the author.