In Kotlin, can a function return either String or Int?

You can use sealed classes, please check official documentation here.

For example, you can write something like this:

sealed class TestResult {
     class Int(val value: Int): TestResult()

     class String(val value: String): TestResult()
}

fun test(n: Int): TestResult = if (n >= 0) TestResult.Int(n) else TestResult.String("$n is negative")

Next you can use when clause to check all possible types in compile type.

5 Likes