Map
有不同的实现
forEach
. 您可以查看源代码。
为了
List
:
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
为了
地图
(这是Java):
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch (IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}
这个
list.forEach
接受一
function type
虽然
map.forEach
接受一
BiConsumer
实例。
为了
表
,如
inline
关键字,可以替换
前额
呼叫
for (value in collection)
{
if("foo".equals(value))
{
return true
}
}
一切都有意义。
你传递到的lambda
地图.foreach
实际上是成员函数的实现
accept
的
双吸收器
接口,类型是
void
. 这就是为什么返回
Boolean
没有道理。即使你只是
return
就这样结束了
接受
方法。因为这不是Kotlin
内联的
函数,它不会结束封闭函数。
Java源代码
消费者
public interface BiConsumer<T, U> {
/**
* Performs this operation on the given arguments.
*
* @param t the first input argument
* @param u the second input argument
*/
void accept(T t, U u);
/**
* Returns a composed {@code BiConsumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code BiConsumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}
如果不进行任何简化,您的函数实际上是这样的:
fun bar(collection: Map<String, String>): Boolean {
val action : BiConsumer<String,String> = object : BiConsumer<String, String> {
override fun accept(t: String, u: String) {
//return boolean is not allow here
//return at here just end the accept function. bar is not affected
}
}
collection.forEach(action)
return false
}
由于Kotlin将单方法接口实现转换为lambda,因此它给您一种错觉,即
地图.foreach
看起来像是接受
功能类型
就像
表
. 事实是lambda被
前额
不是科特林
功能类型
但一
双吸收器
而实际上,最重要的是,它不是
内联的
.