Hey there. I'm trying to use a method with the fol...
# announcements
d
Hey there. I'm trying to use a method with the following signature
Copy code
inline fun <T> withLoggingContext(map: Map<String, String>, body: () -> T): T {
invoking it like this
Copy code
withLoggingContext(browserInfo.toMap()) {
                logger.warn { "Payment context provides no customer ip address" }
            }
leads to following compilation error
Copy code
Error:(28, 13) Kotlin: None of the following functions can be called with the arguments supplied: 
public inline fun <T> withLoggingContext(vararg pair: Pair<String, String>, body: () -> ???): ??? defined in mu
public inline fun <T> withLoggingContext(pair: Pair<String, String>, body: () -> ???): ??? defined in mu
public inline fun <T> withLoggingContext(map: Map<String, String>, body: () -> ???): ??? defined in mu
Help is appreciated
s
The logger doesn't really take a lambda, does it?? Shouldn't it be
logger.warn ( "Payment context provides no customer ip address" )
d
The logger is just fine. It's defined as
Copy code
actual fun warn(msg: () -> Any?)
it complains about the invocation of withLoggingContext
s
what's the return type of the logger? because the withLoggingContext probably wants to return that.
hmm, Unit should handle this correctly 🧐
does browserInfo.toMap() return a
Map<String,String>
?
d
Sorry sometimes I'm just blind. It's
Copy code
Map<String,String?>
. Is there a neat utility function that turns
Map<String,String?>
into
Map<String,String>
like
listOfNotNull
for lists?
Thanks already!
s
map.entries.mapNotNull {(key, value)->value?.let{key to it}}.toMap()
d
thanks
s
i got the syntax a bit wrong 😅 it's
.mapNotNull{key, value->value?.let{key to it}}.toMap()
d
no worries, already got it
s
without
entries
Kotlin wants type annotations. so back to `
Copy code
map.entries.mapNotNull{(key, value)->value?.let{key to it}}.toMap()
filterNotNullValues
and
filterNonNullKeys
: those would be nice! The ticket is already two years old though.
here's the implementation for the first:
Copy code
fun <K: Any, V> Map<K,V>.filterNotNullValues() = this.entries.mapNotNull{(key, value)->value?.let{key to it}}.toMap()
d
I know. I just pointed to it because there the comments already include the implementations for the requested methods
s
where's the fun in that 😂 And here's the implementation that can only be invoked on Maps where the value is actually nullable:
Copy code
fun <K: Any, V:Any> Map<K,V?>.filterNotNullValues(): Map<K,V> = this.entries.mapNotNull{(key, value)->value?.let{key to it}}.toMap()