我正在处理Kotlin-Koans,遇到了这种类型不匹配的情况。我知道这个问题还有其他解决办法,但我想知道我做错了什么。
基本问题似乎是我正在通过flatMap
生成一组Product
val allOrderedProducts = customers.flatMap {it.orders.flatMap {it.products}}.toSet()
然后我用这个作为折叠的接收器
allOrderedProducts.fold(products) { theList, theProduct -> { ... } }
推断出的theProduct
的类型是() -> Product
而不是Product
这是我得到类型不匹配的实际函数(它不是完成,而是语法正确到足以显示类型不匹配)
有人能解释为什么这不起作用吗?
// Return the set of products that were ordered by every customer
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
val products: Set<Product> = setOf()
val allOrderedProducts = customers.flatMap {it.orders.flatMap {it.products}}.toSet()
allOrderedProducts.fold(products) { theList, theProduct ->
customers.all { customer ->
val orderedProducts = customer.orders.flatMap { it.products }
orderedProducts.contains { theProduct } // type mismatch inferred type is () -> Product but Product was expected
}
val ret: Set<Product> = setOf()
ret
}
val retValue: Set<Product> = setOf()
return retValue
}
(免责声明:我根本不是Kotlin专家)
这似乎是一个简单的语法错误;此行:
orderedProducts.contains { theProduct }
应该是
orderedProducts.contains(theProduct)
(将大括号替换为"普通"大括号)