https://kotlinlang.org logo
#codereview
Title
# codereview
d

Dipendra Singh

09/28/2021, 8:47 PM
Hello, Im looking for a way to clean this code. I dont like this part of init empty String, is there other way write this?
Copy code
fun getStreetNameByStreetId(id: String): String {
        val query = Query()
        query.fields().include("name")
        query.addCriteria(Criteria.where("_id").`is`(id))
        var streetName = ""
        mongoTemplate.executeQuery(
            query, STREET_COLLECTION
        ) { document: Document ->
            streetName = document.getValue("name").toString()
        }
        return streetName
    }
s

sbyrne

09/28/2021, 8:55 PM
I would probably write an extension function on MongoTemplate that uses a sequence builder to return a
Sequence<T>
, and in your case where you only want one value, do
val streetName = mongoTemplate.executeQueryToSequence(query,STREET_COLLECTION) { document -> document.getValue("name").toString() }.firstOrNull()
.
👍 1
(
executeQueryToSequence
is the extension function I would write.)
p

Paul Griffith

09/28/2021, 8:58 PM
it looks like
findOne
already exists and is nullable, so something like this would probably be more idiomatic. As a sidenote, this function should probably return
String?
since the lookup is fallible
t

todd.ginsberg

09/28/2021, 9:03 PM
An
apply
might make things a bit cleaner:
Copy code
fun getStreeNameByStreetId(id: String): String {
    val query = Query().apply {
        fields().include("name")
        addCriteria(Criteria.where("_id").`is`(id))
    }
    return mongoTemplate...
}
p

Paul Griffith

09/28/2021, 9:05 PM
d

Dipendra Singh

09/28/2021, 9:12 PM
@Paul Griffith findOne will shout "None of the following functions can be called with the arguments supplied." and Document: id Unresolved reference: _id Im trying to rewrite it somehow but always coming with errors
p

Paul Griffith

09/28/2021, 10:00 PM
🤷 I don't have Spring, MongoDB, or your internal classes in front of me, so I'm just guessing. Your original query syntax may work, it's just not very 'nice' Kotlin
2 Views