Difference between 'contains' and 'containsKey' in Kotlin Map - kotlin

val m = mapOf<String, Int>()
m.contains("Foo")
m.containsKey("Bar")
In Kotlin, there are two methods for Map to check whether the map has specified key: contains and containsKey
I know that key in m is the idiomatic way to check key existence, but I wonder why they have two methods doing same function. Do they have any differences between them? Or are they just some sort of legacy code for compatibility?

They are equivalent. This is the contains method implementation:
#kotlin.internal.InlineOnly
public inline operator fun <#kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.contains(key: K): Boolean = containsKey(key)
According docs:
This method (contains) allows to use the x in map syntax for checking whether
an object is contained in the map.

There is no difference between these methods in Map
contains is just generic function, used in different collections with different behaviour (Example: contains object in Collection, but key in Map)
containsKey and containsValue are Maps specific functions
But contains in Map is just a wrapper for containsKey source code:
public inline operator fun <#kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.contains(key: K): Boolean = containsKey(key)

Related

Map get with null key

I'm confused by Kotlin's null safety features when it comes to maps. I have a Map<String, String>. Yet I can call map.get(null) and it returns null to indicate that the key is not present in the map. I expected a compiler error, because map is a Map<String, String> and not a Map<String?, String>. How come I can pass null for a String argument?
And a related question: is there any type of Map, be it a stdlib one or a third-party implementation, that may throw NullPointerException if I call get(null)? I'm wondering if it is safe to call map.get(s) instead of s?.let { map.get(it) }, for any valid implementation of Map.
Update
The compiler does indeed return an error with map.get(null). But that is not because of null safety, but because the literal null doesn't give the compiler an indication of the type of the parameter being passed. My actual code is more like this:
val map: Map<String, String> = ...
val s: String? = null
val t = map.get(s)
The above compiles fine, and returns null. How come, when the key is supposed to be a String which is non-nullable?
The get method in Map is declared like this:
abstract operator fun get(key: K): V?
so for a Map<String, String>, its get method should only take Strings.
However, there is another get extension function, with the receiver type of Map<out K, V>:
operator fun <K, V> Map<out K, V>.get(key: K): V?
The covariant out K is what makes all the difference here. Map<String, String> is a kind of Map<out String?, String>, because String is a subtype of String?. As far as this get is concerned, a map with dogs as its keys "is a" map with animals as its keys.
val notNullableMap = mapOf("1" to "2")
// this compiles, showing that Map<String, String> is a kind of Map<out String?, String>
val nullableMap: Map<out String?, String> = notNullableMap
And this is why you can pass in a String? into map.get, where map is a Map<String, String>. The map gets treated as "a kind of" Map<String?, String> because of the covariant out K.
And a related question: is there any type of Map, be it a stdlib one or a third-party implementation, that may throw NullPointerException if I call get(null)?
Yes, on the JVM, TreeMap (with a comparator that doesn't handle nulls) doesn't support null keys. Compare:
val map = TreeMap<Int, Int>()
println(map[null as Int?]) // exception!
and:
val map = TreeMap<Int, Int>(Comparator.nullsLast(Comparator.naturalOrder()))
println(map[null as Int?]) // null
However, note that since the problematic get is an extension function that is available on every Map, you cannot prevent someone from passing in a nullable thing to your map at compile time, as long as your map implements Map.

Why generic form of groupBy in Kotlin is not enough?

Kotlin documentation for groupBy shows special form for every type, like ByteArray, IntArray. Why it is so, why the single generic form is not enough?
inline fun <T, K> Array<out T>.groupBy(
keySelector: (T) -> K
): Map<K, List<T>>
The snippet from Kotlin documentation
inline fun <T, K> Array<out T>.groupBy(
keySelector: (T) -> K
): Map<K, List<T>>
inline fun <K> ByteArray.groupBy(
keySelector: (Byte) -> K
): Map<K, List<Byte>>
inline fun <K> ShortArray.groupBy(
keySelector: (Short) -> K
): Map<K, List<Short>>
inline fun <K> IntArray.groupBy(
keySelector: (Int) -> K
): Map<K, List<Int>>
...
Question 2
It seems like IntArray is not subclassing the Array and that's probably the reason why it is necessary.
So, I wonder - if I would like to add my own function, let's say verySpecialGroupBy - does it means that I would also need to specify not just one such function - but repeat it for every array type?
Or it's a very specific and rare case when you would need to use those special arrays and in practice you can just define your function for generic Array and ignore the rest?
Those array specializations are for arrays of primitive types. So in your example of creating a verySpecialGroupBy function, you would only need to repeat it for each specialization if you wanted to use it with primitive type arrays.
You can read more about the need of primitive type array in this Kotlin discussion thread.

Type inference for higher order functions with generic return types

The following example is perfectly legal in Kotlin 1.3.21:
fun <T> foo(bar: T): T = bar
val t: Int = foo(1) // No need to declare foo<Int>(1) explicitly
But why doesn't type inference work for higher order functions?
fun <T> foo() = fun(bar: T): T = bar
val t: Int = foo()(1) // Compile error: Type inference failed...
When using higher order functions, Kotlin forces the call site to be:
val t = foo<Int>()(1)
Even if the return type of foo is specified explicitly, type inference still fails:
fun <T> foo(): (T) -> T = fun(bar: T): T = bar
val t: Int = foo()(1) // Compile error: Type inference failed...
However, when the generic type parameter is shared with the outer function, it works!
fun <T> foo(baz: T) = fun (bar: T): T = bar
val t: Int = foo(1)(1) // Horray! But I want to write foo()(1) instead...
How do I write the function foo so that foo()(1) will compile, where bar is a generic type?
I am not an expert on how type inference works, but the basic rule is: At the point of use the compiler must know all types in the expression being used.
So from my understanding is that:
foo() <- using type information here
foo()(1) <- providing the information here
Looks like type inference doesn't work 'backward'
val foo = foo<Int>()//create function
val bar = foo(1)//call function
To put it in simple (possibly over-simplified) terms, when you call a dynamically generated function, such as the return value of a higher-order function, it's not actually a function call, it's just syntactic sugar for the invoke function.
At the syntax level, Kotlin treats objects with return types like () -> A and (A, B) -> C like they are normal functions - it allows you to call them by just attaching arguments in parenthesis. This is why you can do foo<Int>()(1) - foo<Int>() returns an object of type (Int) -> (Int), which is then called with 1 as an argument.
However, under the hood, these "function objects" aren't really functions, they are just plain objects with an invoke operator method. So for example, function objects that take 1 argument and return a value are really just instances of the special interface Function1 which looks something like this
interface Function1<A, R> {
operator fun invoke(a: A): R
}
Any class with operator fun invoke can be called like a function i.e. instead of foo.invoke(bar, baz) you can just call foo(bar, baz). Kotlin has several built-in classes like this named Function, Function1, Function2, Function<number of args> etc. used to represent function objects. So when you call foo<Int>()(1), what you are actually calling is foo<Int>().invoke(1). You can confirm this by decompiling the bytecode.
So what does this have to do with type inference? Well when you call foo()(1), you are actually calling foo().invoke(1) with a little syntactic sugar, which makes it a bit easier to see why inference fails. The right hand side of the dot operator cannot be used to infer types for the left hand side, because the left hand side has to be evaluated first. So the type for foo has to be explicitly stated as foo<Int>.
Just played around with it a bit and sharing some thoughts, basically answering the last question "How do I write the function foo so that foo()(1) will compile, where bar is a generic type?":
A simple workaround but then you give up your higher order function (or you need to wrap it) is to have an intermediary object in place, e.g.:
object FooOp {
operator fun <T> invoke(t : T) = t
}
with a foo-method similar as to follows:
fun foo() = FooOp
Of course that's not really the same, as you basically work around the first generic function. It's basically nearly the same as just having 1 function that returns the type we want and therefore it's also able to infer the type again.
An alternative to your problem could be the following. Just add another function that actually specifies the type:
fun <T> foo() = fun(bar: T): T = bar
#JvmName("fooInt")
fun foo() = fun(bar : Int) = bar
The following two will then succeed:
val t: Int = foo()(1)
val t2: String = foo<String>()("...")
but... (besides potentially needing lots of overloads) it isn't possible to define another function similar to the following:
#JvmName("fooString")
fun foo() = fun(bar : String) = bar
If you define that function it will give you an error similar as to follows:
Conflicting overloads: #JvmName public final fun foo(): (Int) -> Int defined in XXX, #JvmName public final fun foo(): (String) -> String defined in XXX
But maybe you are able to construct something with that?
Otherwise I do not have an answer to why it is infered and why it is not.

In Kotlin, how do I idiomatically access nullable nested map values, or return a default?

Quick Kotlin best practices question, as I couldn't really work out the best way to do this from the documentation.
Assume I have the following nested map (typing specified explicitly for the purpose of this question):
val userWidgetCount: Map<String, Map<String, Int>> = mapOf(
"rikbrown" to mapOf(
"widgetTypeA" to 1,
"widgetTypeB" to 2))
Can the following mode be any more succinct?
fun getUserWidgetCount(username: String, widgetType: String): Int {
return userWidgetCount[username]?.get(widgetType)?:0
}
In other words, I want to return the user widget count iff the user is known and they have an entry for that widget type, otherwise zero. In particular I saw I can use [] syntax to access the map initially, but I couldn't see a way to do this at the second level after using ?..
I would use an extension operator method for that.
// Option 1
operator fun <K, V> Map<K, V>?.get(key: K) = this?.get(key)
// Option 2
operator fun <K, K2, V> Map<K, Map<K2, V>>.get(key1: K, key2: K2): V? = get(key1)?.get(key2)
Option 1:
Define an extension that provides get operator for nullable map. In Kotlin's stdlib such approach appears with Any?.toString() extension method.
fun getUserWidgetCount(username: String, widgetType: String): Int {
return userWidgetCount[username][widgetType] ?: 0
}
Option 2:
Create a special extension for map of maps. In my opinion, it is better because it shows the contract of the map of maps better than two gets in a row.
fun getUserWidgetCount(username: String, widgetType: String): Int {
return userWidgetCount[username, widgetType] ?: 0
}

BiMap / 2-way hashmap in Kotlin

is there a bidirectional hashmap for kotlin?
If not - what is the best way to express this in kotlin?
Including guava to get the BiMap from there feels like shooting with a very big gun on a very little target - no solution that I can imagine currently feels right - the best thing I have in mind is to write a custom class for it
I need a simple BiMap implementation too so decided to create a little library called bimap.
The implementation of BiMap is quite straightforward but it contains a tricky part, which is a set of entries, keys and values. I'll try to explain some details of the implementation but you can find the full implementation on GitHub.
First, we need to define interfaces for an immutable and a mutable BiMaps.
interface BiMap<K : Any, V : Any> : Map<K, V> {
override val values: Set<V>
val inverse: BiMap<V, K>
}
interface MutableBiMap<K : Any, V : Any> : BiMap<K, V>, MutableMap<K, V> {
override val values: MutableSet<V>
override val inverse: MutableBiMap<V, K>
fun forcePut(key: K, value: V): V?
}
Please, notice that BiMap.values returns a Set instead of a Collection. Also BiMap.put(K, V) throws an exception when the BiMap already contains a given value. If you want to replace pairs (K1, V1) and (K2, V2) with (K1, V2) you need to call forcePut(K, V). And finally you may get an inverse BiMap to access its keys by values.
The BiMap is implemented using two regular maps:
val direct: MutableMap<K, V>
val reverse: MutableMap<V, K>
The inverse BiMap can be created by just swapping the direct and the reverse maps. My implementation provides an invariant bimap.inverse.inverse === bimap but that's not necessary.
As mentioned earlier the forcePut(K, V) method can replace pairs (K1, V1) and (K2, V2) with (K1, V2). First it checks what the current value for K1 is and removes it from the reverse map. Then it finds a key for value V2 and removes it from the direct map. And then the method inserts the given pair to both maps. Here's how it looks in code.
override fun forcePut(key: K, value: V): V? {
val oldValue = direct.put(key, value)
oldValue?.let { reverse.remove(it) }
val oldKey = reverse.put(value, key)
oldKey?.let { direct.remove(it) }
return oldValue
}
Implementations of Map and MutableMap methods are quite simple so I will not provide details for them here. They just perform an operation on both maps.
The most complicated part is entries, keys and values. In my implementation I create a Set that delegates all method invocations to direct.entries and handle modification of entries. Every modification happens in a try/catch block so that the BiMap remains in consistent state when an exception is thrown. Moreover, iterators and mutable entries are wrapped in similar classes. Unfortunately, it makes iteration over entries much less efficient because an additional MutableMap.MutableEntry wrapper is created on every iteration step.
If speed is not a priority ( O(n) complexity ) you can create an extension function: map.getKey(value)
/**
* Returns the first key corresponding to the given [value], or `null`
* if such a value is not present in the map.
*/
fun <K, V> Map<K, V>.getKey(value: V) =
entries.firstOrNull { it.value == value }?.key
FWIW, you can get the inverse of the map in Kotlin using an extension function:
fun <K, V> Map<K, V>.inverseMap() = map { Pair(it.value, it.key) }.toMap()
The map operator can be used to iterate over the List of key-value pairs in the Map, then convert back to a map using .toMap().
Well, you are right - as it stated in a similar question for Java "Bi-directional Map in Java?", Kotlin does not have BiMap out of the box.
The workarounds include using Guava and creating a custom class using two usual maps:
class BiMap<K, V>() {
private keyValues = mutableMapOf<K, V>()
private valueKeys = mutableMapOf<V, K>()
operator fun get(key: K) = ...
operator fun get(value: V) = ...
...
}
This solution should not be slower or take more memory than a more sophisticated one. Although I am not sure what happens when K is the same as V.
The cleanest solution to to use Guava and create an extension function that turns a Map into a BiMap. This follows the semantics of Kotlin's other Map conversions as well. Although Guava might have a bit of overhead, you gain the flexibility to add more extension functions wrappers in the future. You can always remove Guava in the future and replace the extension function with another implementation.
First declare your extension function.
fun <K, V> Map<K, V>.toBiMap() = HashBiMap.create(this)
Then use it like this:
mutableMapOf("foo" to "bar", "me" to "you").toBiMap()