What's the difference between the type `(T) -> ...
# getting-started
m
What's the difference between the type
(T) -> Unit
and the type
Consumer<in T>
for function parameters? When I use the first I get a lengthy error with the
foo(...) { t: T -> ... }
implementation, but the second works just fine.
h
(T) -> Unit
uses Kotlin’s function type syntax and exists on all platforms, whereas
Consumer<in T>
uses the Java standard library. In general you should always use the former, but I use
Consumer<in T>
sometimes for legacy functions that are meant to be called from Java code (otherwise you’d have to explicitly return
Unit.INSTANCE
). I don’t know what would be causing such an error from Kotlin; if you want, could you post it here?
1
m
Sure! I have the following definition in one project:
Copy code
data class MelodiaGUIItem(..., val clickFunc: (InventoryClickEvent) -> Unit)
And I use it as such in another project:
Copy code
MelodiaGUIItem(...) { e: InventoryClickEvent -> e.whoClicked.sendMessage("Greenhouse") }
I have linked the projects together correctly as everything else I've been able to use just fine, however when I try this I get the following error:
[T]he class loader 'ScovillePlugin-1.0-SNAPSHOT-all.jar' @253c7e22 of the current class, dev/meluhdy/scovilleplugin/gui/pk/PkGUI, and the class loader 'Melodia-1.0-SNAPSHOT-all.jar' @119fc272 for the method's defining class, dev/meluhdy/melodia/gui/MelodiaGUIItem, have different Class objects for the type kotlin/jvm/functions/Function1 used in the signature
I've made sure the kotlin and gradle versions for both projects are the same, so I'm confused why it's saying they have different class objects for a built-in
@homchom Just a bump in case you haven't seen; it's alright if this is too old though, but I still haven't figured out why the former doesn't work. Thanks for the clarification between the two though!