https://kotlinlang.org logo
Title
t

tipsy

05/06/2018, 4:56 PM
i have a setter method:
fromJson(JsonToObjectMapper jsonToObjectMapper)
(java), which configures how my library does json-mapping:
public interface JsonToObjectMapper {
    <T> T map(String json, Class<T> targetClass);
}
calling this method works fine from java, but kotlin is unable to infer types. if i try to to:
val gson = GsonBuilder().create()
myPlugin.fromJson(gson::fromJson)
i just get
None of the following functions can be called with the arguments supplied.
any ideas?
a

Andreas Sinz

05/06/2018, 5:24 PM
@tipsy
JsonToObjectMapper
is a kotlin interface, right?
t

tipsy

05/06/2018, 5:25 PM
i've tried both java and kotlin, java gets me bit farther (the one i pasted here is java)
a

Andreas Sinz

05/06/2018, 5:27 PM
if you define the interface in java, you can try
myPlugin.fromJson { json, cls -> gson.fromJson(json, cls) }
i don't think SAM conversion works with
gson::fromJson
t

tipsy

05/06/2018, 5:31 PM
yeah, and you can't have lambdas with generics
😞
a

Andreas Sinz

05/06/2018, 5:33 PM
does
JsonToObjectMapper
only have a single method?
t

tipsy

05/06/2018, 5:33 PM
yes
a

Andreas Sinz

05/06/2018, 5:35 PM
you could use a function type instead of an interface:
typealias JsonToObjectMapper<T> = (String, Class<T>) -> T

fun MyPlugin.fromJson(map: JsonToObjectMapper<T>) {
    ....
}
then you can use any function that has the same shape, e. g.
myPlugin.fromJson(gson::fromJson)
works
t

tipsy

05/06/2018, 5:37 PM
i believe this will work fine from kotlin, but not java
a

Andreas Sinz

05/06/2018, 5:42 PM
it should work just fine (if
kotlin-stdlib
is included in the java project), function types are just functional interfaces
t

tipsy

05/06/2018, 5:44 PM
alright, i'll give it a try, thanks
Type inference failed: Not enough information to infer parameter T in 

fun <T> fromJson(map: JsonToObjectMapper<T> /* = (String, Class<T>) → T */): Unit
worked in java though, so that's good