Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin's forEach hides original forEach

I have created a set using Collections.synchronizedSet<T>(mutableSetOf<T>()).
SynchronizedSet has its own implementation of forEach (synchronized) that differs from the one provided by Iterable.forEach (not synchronized), however Kotlin's Iterable.forEach is annotated with @HidesMembers, so it gets called instead of the synchronized one.

How do I get back the synchronized version of forEach?

like image 790
binarynoise Avatar asked Aug 31 '25 03:08

binarynoise


1 Answers

The forEach you are looking for is a method on java.lang.Iterable interface so casting will work.

A (quite ugly) example:

import java.util.Collections

fun main() {
    val col  = Collections.synchronizedCollection(mutableSetOf(1,2,3))
    (col as java.lang.Iterable<*>).forEach { println(it) }
}  

The IDEA debugger hits the expected code in SynchronizedCollection.forEach:

public void forEach(Consumer<? super E> consumer) {
    synchronized (mutex) {c.forEach(consumer);}
}
like image 106
David Soroko Avatar answered Sep 03 '25 00:09

David Soroko