Micah Smith
Micah Smith

Reputation: 311

How to cast an explicit named lambda argument in kotlin mapping functions

Given a functor of a generic Any type, how can I cast an explicity named argument? For instance, I have a JsonArray (vertx) that is essentially a type of List<Any>... I can cast to JsonObject using the implicit it, but if I were to name it participant how can I cast as JsonObject?

val participants = conversation
    .getJsonArray("participants")
    .map{ (it as JsonObject)
        it.getInteger("id")
    }

My IDE complains no matter what I throw at it. Is this even possible? Something like:

val participants = conversation
    .getJsonArray("participants")
    .map{ (participant as JsonObject) ->
        participant.getInteger("id")
    }

Upvotes: 0

Views: 448

Answers (1)

Nikolai  Shevchenko
Nikolai Shevchenko

Reputation: 7521

Like @gidds wrote, following is correct:

val participants = conversation
    .getJsonArray("participants")
    .map { 
       (it as JsonObject).getInteger("id")
    }

For explicit arguments you can write like this:

val participants = conversation
    .getJsonArray("participants")
    .map { participant -> 
       (participant as JsonObject).getInteger("id")
    }

Upvotes: 1

Related Questions