Computer scienceProgramming languagesKotlinAdvanced featuresDSL

Contracts

Add to positive

Report a typo

We have a function printIncrement that prints the incrementation of an Int if it is positive:

fun printIncrement(value: Int?) {
    val x: Int? = value
    if (x.isPositive()) {
        println(x + 1)
    } else {
        println("Can't increment a negative value")
    }
}

Complete the provided function isPositive to make it verify if an Int is positive and not null. Also, it must contain a contract that implies that when the function returns true, the receiver is not null.

Sample Input 1:

-4

Sample Output 1:

Can't increment a negative value

Sample Input 2:

9

Sample Output 2:

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

@OptIn(ExperimentalContracts::class)
fun Int?.isPositive(): Boolean {

// Your code goes here

}

Create a free account to access the full topic