I'm writing a method that other people on my team ...
# getting-started
c
I'm writing a method that other people on my team are going to use and the method has to accept a
mapOf
size 1. Is there any way to enforce that? Basically my method is
fun myFunction(event: Map)
but technically right now it can be mis-used because you can add more than 1 item in the map. Ideas?
e
isn't that just a Pair?
🤔 1
c
Is it? Lets see. FWIW. I tried Key.Entry with no luck. and I'm boxed into using a map because thats what i need for a moshi serialization that im doing (my question from yest pointed me to a map #squarelibraries)
e
if you want it to serialize like a map, you'll need custom logic. I haven't used Moshi in a long time though, don't remember how that's done
c
dang. yeah. Just tried a pair and it seraializes the
first
and
second
property
I thought Map.Entry might do it, but seems like I can't just init a Map.Entry
e
there is AbstractMap.SimpleEntry on JVM but that won't serialize to what you want either
c
thanks. back to the drawing board. backend team be damned.
l
Couldn't you get the
Pair<A, B>
and internally transform into a
Map<A, B>
with
mapOf(pair)
?
Copy code
fun myFunction(event: Pair<String, Any>) {
    val mapEvent = mapOf(event)
    // Go to Moshi...
}
c
yeah. i think thats what im going to fallback to. i haven't tried it yet, but pappering over the issue here makes sense i think
y
In general, a function should probably expose exactly what it needs as parameters, and then only internally transform them for any quirks (because those are implementation details)
👍 1
r
FWIW my experience has been that I've generally ended up refactoring
fun myFunction(pair: Pair<String, Any>)
to
fun myFunction(key: String, value: Any)
. It lets you give the two values sensible parameter names in the function, reduces the amount of generics in the type signatures, and even if the caller has a Pair it's trivial to decompose it.
4