https://kotlinlang.org logo
Title
c

Colton Idle

05/24/2023, 12:34 PM
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

ephemient

05/24/2023, 12:35 PM
isn't that just a Pair?
c

Colton Idle

05/24/2023, 12:38 PM
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

ephemient

05/24/2023, 12:39 PM
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

Colton Idle

05/24/2023, 12:41 PM
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

ephemient

05/24/2023, 12:46 PM
there is AbstractMap.SimpleEntry on JVM but that won't serialize to what you want either
c

Colton Idle

05/24/2023, 12:53 PM
thanks. back to the drawing board. backend team be damned.
l

lazynoda

05/24/2023, 1:09 PM
Couldn't you get the
Pair<A, B>
and internally transform into a
Map<A, B>
with
mapOf(pair)
?
fun myFunction(event: Pair<String, Any>) {
    val mapEvent = mapOf(event)
    // Go to Moshi...
}
c

Colton Idle

05/24/2023, 1:52 PM
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

Youssef Shoaib [MOD]

05/24/2023, 2:46 PM
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)
r

Rob Elliot

05/24/2023, 3:05 PM
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.