Computer scienceProgramming languagesKotlinAdvanced featuresDSL

Contracts

Theory

Is string?

Report a typo

We have a function strLength that is trying to get the length of a string:

fun strLength(value: Any?): Int {
    return if (value.isString()) {
        value.length
    } else {
        0
    }
}

fun Any?.isString(): Boolean {
    return this is String
}

However, it won't compile because the compiler doesn't know that the isString function guarantees that value is a String when it returns true.

Your task is to add a contract to the isString function that tells the compiler that value can be smartcast to String when isString returns true.

Sample Input 1:

Hello, Kotlin!

Sample Output 1:

14
Write a program in Kotlin
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract

@OptIn(ExperimentalContracts::class)
fun Any?.isString(): Boolean {

// Your code goes here

return this is String
}
___

Create a free account to access the full topic