Kotlin provides TODO()
function which we can use as a placeholder in code or function which is yet to be implemented.
Suppose we are working on a project that involves three functions :
fun load(name: String): String
fun store(name: String, content: String): Boolean
fun count(): Int
We declared these functions at once but will define them functions one by one. After defining the load()
function, we want to run the program to test it :
fun load(name: String): String {
}
fun store(name: String, content: String): Boolean { }
fun count(): Int { }
Problem : The other two functions are yet to be defined and they have a return type so compiler shows the following error and we can’t run our code :
A 'return' expression required in a function with a block body ('{...}')
We have two options, either we can return a dummy value or comment out the function for now :
fun store(name: String, content: String): Boolean = false
This works, but there is a better way to do the same. We can use the TODO()
function as a placeholder :
fun store(name: String, content: String): Boolean = TODO()
fun count(): Int = TODO()
This hides the error and we can run our code successfully. Note that we need not write any return statement and it works for any return type!
Once we have implemented the missing code, we can simply replace the TODO()
function with the actual implementation.
If we invoke a function which is defined as TODO()
, a NotImplementedError exception is thrown :
fun count(): Int = TODO()
fun main() {
print(count())
}
This is good because if we would have defined a dummy value, we couldn’t know that the function is yet to be implemented. But using TODO()
, this error reminds us to implement the function before use.
Optionally, we can provide a reason String to the TODO()
function :
TODO()
fun count(): Int = TODO("Waiting for version upgrade")
TODO()
function always throws an error, so it has Nothing
as return type :
fun TODO(): Nothing = throw NotImplementedError()
fun TODO(reason: String): Nothing = throw NotImplementedError("An operation is not implemented: $reason")