Home > Enterprise >  How can I import kotlin functions to java classes?
How can I import kotlin functions to java classes?

Time:02-10

I am currently using KotlinModule class in my java file by importing import com.fasterxml.jackson.module.kotlin.KotlinModule;, but in recent jackson library upgrade (using 2.13) it is has been depricated. I was looking for the new convention, and came across this https://github.com/FasterXML/jackson-module-kotlin#usage

however I am not able to load the recommended functions in java file, i think that only works in Kotlin file. Is there an alternative?

CodePudding user response:

This module uses Kotlin extension functions, they are all defined in an Extensions.kt file and as such are accessible by importing the ExtensionsKt class. For example :

import com.fasterxml.jackson.module.kotlin.ExtensionsKt;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = ExtensionsKt.jacksonObjectMapper();

If the method extends a type, for example in Kotlin :

val mapper = ObjectMapper().registerKotlinModule()

The method is defined in kotlin as :

fun ObjectMapper.registerKotlinModule(): ObjectMapper

It will be converted in java to :

public static final ObjectMapper registerKotlinModule(@NotNull ObjectMapper $this$registerKotlinModule)

So to use it, you need to pass the extended type :

ObjectMapper mapper = ExtensionsKt.registerKotlinModule(new ObjectMapper());
  • Related