DEV Community

Kenji Tomita
Kenji Tomita

Posted on • Updated on

Learning about Explicit API mode in Kotlin

Kotlin 1.4 allows you to enforce styles in explicit API mode. You can choose the error or warning option. It's feature for library authors. Let's try explicit API mode with the sample code.

Add the following line to your gradle build script. Let me explain using build.gradle.kts as an example. For groovy, see here.

// build.gradle.kts
kotlin {
    // for strict mode
    explicitApi()
}
Enter fullscreen mode Exit fullscreen mode

Next, create a HelloWorld.kt and add the following.

// HelloWorld.kt
fun main() {
    printHelloWorld()
}

fun printHelloWorld() {
    println(getHelloWorld())
}

fun getHelloWorld() = "Hello World"
Enter fullscreen mode Exit fullscreen mode

You're ready to try explicit API mode. Let's build it.

// HelloWorld.kt
fun main() { // Visibility must be specified in explicit API mode
    printHelloWorld()
}

fun printHelloWorld() { // Visibility must be specified in explicit API mode 
    println(getHelloWorld())
}

fun getHelloWorld() = "Hello World" // Visibility must be specified in explicit API mode. Return type must be specified in explicit API mode 
Enter fullscreen mode Exit fullscreen mode

You got an error about Visibility must be specified in explicit API and Return type must be specified in explicit API mode. Let's try again, explicitly specifying the visibility modifiers and return type.

// HelloWorld.kt
public fun main() {
    printHelloWorld() // Hello World
}

private fun printHelloWorld() {
    println(getHelloWorld())
}

private fun getHelloWorld(): String = "Hello World"
Enter fullscreen mode Exit fullscreen mode

Hello World is output. If you want to use the warning option instead of the strict option, use explicitApiWarning(). For groovy, see here. Especially Explicit API mode is very convenient for library developers.

References are as follows.

Top comments (0)