Kotlin - An interface for pairs

Viewed 111

I'm new to Kotlin, and unsure how to abstract the following.

So for example I have this:

metadataOf(
   "sId" to "123",
   "uId" to "456"
)

where metadataOf() looks like this

fun <VALUE> metadataOf(vararg pairs: Pair<String, VALUE>) =
    MetaData.from(pairs.toMap())!!

I'd like that

metadataOf(
   "sId" to "123",
   "uId" to "456"
)

To be standarised, so say something like metadata.message or metadataFrom(message) would produce those 2 pairs for me. (And of course in the future if I added more and I could easily do so in one place)

How would I go about writing this?

Any help appreciated.

2 Answers

Sounds like what you really wanted is:

data class SMetadata(val sId: String, val uId: String)

and

//fun metadataOf(vararg sMetadatas: SMetaData) =
//    MetaData.from(sMetaDatas.map { mapOf("sId" to it.sId, "uId" to it.uId) })

and

//metadataOf(
//   SMetaData(sId = "123", uId = "456")
//)

EDIT: apparently all you really wanted was

fun SMetaData.toMetaData() = MetaData.from(mapOf("sId" to sId, "uId" to uId))

You can make your own Pair implementation along with an infix function, lets call it MyPair and give it the same implementation as the original one:

fun main() {
    listOf(
        "s1" pair "s2",
        "k1" pair "k2"
    )
}

public data class MyPair<out A, out B>(
    public val first: A,
    public val second: B
) : Serializable {
    public override fun toString(): String = "($first, $second)"
}

public infix fun <A, B> A.pair(that: B): MyPair<A, B> = MyPair(this, that)
Related