Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Monday, October 24, 2016

Disambiguating Null Arguments in Kotlin

To define a function argument that can accept a null value in Kotlin, you use the question mark (?) operator.  For example,

fun bar(name : String?) { // ... do something

Can accept both a String argument like "Hello, World!" and a null.  If you have another version of bar() that accepts a nullable argument, say

fun bar(name : Int?) { // ... do something w. an Int

You'll run into a problem if you call


To disambiguate this, you need to provide type into to Kotlin. That type info should be a nullable type. In the following code, a method "foo" is updated with a newer version. Both functions can coexist when non-null arguments are passed. The Kotlin as keyword is used to specify exactly which function is to be used for the null value (and the code compiled).

class NewClass {}

@Deprecated("use NewClass instead")
class ObsoletedClass {}

fun foo( obj : NewClass? ) {
    println("new implementation based on new arg")

fun foo( obj : ObsoletedClass? ) {
    println("old implementation based on old arg")

fun main(args : Array) {

    // call using new argument
    foo( NewClass() )

    // call using old argument
    foo( ObsoletedClass() )

    // call to new function w. new null argument
    foo( null as NewClass? )

    // call to old function w. old null argument
    foo( null as ObsoletedClass? )


The result of running the program is the following.

/opt/jdk1.8.0_102/bin/java ...
new implementation based on new arg
old implementation based on old arg
new implementation based on new arg
old implementation based on old arg

Process finished with exit code 0

You can also provide a no-arg version of foo, but if foo had a longer signature, it may not be worthwhile to support a set of varying arities.

No comments:

Post a Comment