Read this answer for Java 8, everything it says also applies to Kotlin:
The additions made to the Java language do not render every old concept outdated. In fact, the Visitor pattern is very good at supporting adding of new operations.
This holds true for Kotlin. Like Java 8 it has Lambdas, SAM conversions, and interfaces that allow default implementations.
One change is if you are doing class instance type checking, instead of using a large if
statement for each instanceof
check, use the when
expression in Kotlin:
On that same Stackoverflow page in a different answer it talks about Lambdas being used and shows if
statement in Java deciding which lambda to call. Instead of their Java sample:
if (animal instanceof Cat) {
catAction.accept((Cat) animal);
} else if (animal instanceof Dog) {
dogAction.accept((Dog) animal);
} else if (animal instanceof Fish) {
fishAction.accept((Fish) animal);
} else if (animal instanceof Bird) {
birdAction.accept((Bird) animal);
} else {
throw new AssertionError(animal.getClass());
}
Use this Kotlin:
when (animal) {
is Cat -> catAction.accept(animal)
is Dog -> dogAction.accept(animal)
is Fish -> fishAction.accept(animal)
is Bird -> birdAction.accept(animal)
else -> throw AssertionError(animal.javaClass)
}
In Kotlin you don't need to cast since a smart cast is automatically made when the compiler sees the is
check for the instance type.
Also in Kotlin you can use Sealed Classes to represent your possible options in the hierarchy and then the compiler can determine if you have exhausted all cases meaning you do not need the else
in the when
statement.
Otherwise what holds true on that page, and other common answers to the same question is good information for Kotlin. I don't think it is as common to see an actual literal visitor pattern as much in Java 8, Scala or Kotlin, but rather some variation using lambdas and/or pattern matching.
Other related articles: