Given a tuple with elements of type A
and another type parametrised in A
:
trait Writer[-A] { def write(a: A): Unit }
case class Write[A](value: A, writer: Writer[A])
And a use site:
trait Cache { def store[A](value: A, writer: Writer[A]): Unit }
Why does the following work as expected, using the tuple's extractor:
def test1(set: Set[Write[_]], cache: Cache): Unit =
set.foreach {
case Write(value, writer) => cache.store(value, writer)
}
But the following fails:
def test2(set: Set[Write[_]], cache: Cache ): Unit =
set.foreach { write =>
cache.store(write.value, write.writer)
}
with error message
found : Writer[_$1] where type _$1
required: Writer[Any]
cache.store(write.value, write.writer)
^
Can I fix the second form (test2
) to compile properly?
EDIT
Departing from the ideas by Owen I tried out if I can make it work without pattern matching at all (which is what I wanted in the first place). Here are two more strange cases, one working, the other not:
// does not work
def test3(set: Set[Write[_]], cache: Cache): Unit = {
def process[A](write: Write[A]): Unit =
cache.store(write.value, write.writer)
set.foreach(process)
}
// _does work_
def test4(set: Set[Write[_]], cache: Cache): Unit = {
def process[A](write: Write[A]): Unit =
cache.store(write.value, write.writer)
set.foreach(w => process(w))
}
Still pretty obscure to me...