Home > other >  Kotlin - Need return type String but got any instead
Kotlin - Need return type String but got any instead

Time:10-27

I need this function to return a String so I can call it in another function but instead I got any. How can I make it return a String?

private fun getValue(text: String){
myMap.forEach { (k, v) -> v.find {it.key == text}?.values?.joinToString(separator = "#") ?: ""}}

myMap is a Map<UUIDint, List<SomeAttribute>>

SomeAttribute is a data class

data class SomeAttribute(
  var key: String = "",
  var values: List<String> = ArrayList()
)

I want the output String to look like this 122PR or 122PR#374DH respectively.

CodePudding user response:

forEach method returns Unit. You need to do some side-effect inside it (modify some variable defined beforehand) and return this variable. But it's better to use other methods, which will immediately return what you need.

Depending on what exactly String you want to get from this Map there are several options:

  1. If you want to get values of first met SomeAttribute which has required text as a key, then you need to:
myMap.values.flatten().find { it.key == text }?.values?.joinToString(separator = "#")
  1. If you want to get values of all first met SomeAttributes in each List<SomeAttribute>, which have required text as a key, then you need to:
myMap.values.flatMap { v -> v.find { it.key == text }?.values ?: emptyList() }.joinToString(separator = "#")
  1. If you want to get values of all SomeAttributes which has required text as a key in each List<SomeAttribute>, then you need to:
myMap.values.flatMap { v -> v.filter { it.key == text } }.map { it.values }.joinToString(separator = "#")

CodePudding user response:

if you want it to return the first match it has you could do like this:

private fun getValue(text: String) : String {
    myMap.forEach { (_, v) -> v.find {it.key == text}?.values?.joinToString(separator = "#")?.let { return it }}
    return ""
}
  • Related