Some of the benefits of working with Kotlin and Java 8 include not having to litter your code with anonymous inner classes. They’re ugly and require too much boilerplate in order to accomplish what should be simple tasks. Figuring out the syntax can be less than trivial when learning the languages or how to use these new features, however.
Kotlin and Java 8 both support SAM conversions, which is essentially using a lambda expression to implement a functional interface as long as the signature of the lambda expression matches the signature of the single method in the interface.
Working with JdbcOperations
in some Spring code recently, it took me a little while to figure out exactly how to do this in Kotlin. Here’s what I figured out:
fun main(args: Array<String>) {
val jdbc = JdbcOperations()
val mapper:RowMapper<Person> = RowMapper { r, i -> Person(name=r.get("name")!!, email=r.get("email")!!) }
val people = jdbc.query("some query", mapper)
}
The same in Java
void main(String[] args) {
RowMapper<Person> mapper = (Map<String,String> row, int index) ->
new Person(row.get("name"), row.get("email"));
jdbc.query("some query", mapper);
}
or
class Demo {
public List<Person> runDemo() {
JdbcOperations jdbc = new JdbcOperations();
return jdbc.query("some query", this::mapToPerson);
}
Person mapToPerson(Map<String, String> row, int index) {
return new Person(row.get("name"), row.get("email"));
}
}
Read more on SAM Conversions on kotlinlang.org.