DEV Community

loading...

Learning about Explicit API mode in Kotlin

tommykw profile image Kenji Tomita ・2 min read

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

I 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. Explicit API mode It's very convenient.

References are as follows.

Discussion (0)

pic
Editor guide