trait Foo { }
class FooImpl extends Foo {}
class Sample
{
val m: Map[_ <: Foo, String] = Map()
val foo: Foo = new FooImpl
// This line fails to compile
m(foo)
val m2: Map[Foo, String] = Map()
// This line compiles fine (but will throw at runtime)
m2(foo)
}
我使用的是scala 2.12,通配符版本无法编译:
[info] Compiling 1 Scala source to /test/scala/target/scala-2.12/classes ...
[error] /test/scala/src/main/scala/Test.scala:10:7: type mismatch;
[error] found : Sample.this.foo.type (with underlying type Foo)
[error] required: _$1
[error] m(foo)
[error] ^
[error] one error found
有没有可能从第一张地图上得到具体的数值(
m
m.filter({(k,v) => k.equals(foo)})
? 在爪哇,我可以做到
m.get(foo)
而且Scala似乎不太可能强迫我比Java更详细、更不清晰。