2

I have a seemingly very simple Scala question that's driving me crazy. This:

class A
class B extends A
class C { def foo(a: Array[_ <: A]) { a(0) = a(1) }}

Doesn't compile. It says:

scala> class C { def foo(a: Array[_ <: A]) { a(0) = a(1) }}
<console>:8: error: type mismatch;
 found   : (some other)_$1(in method foo)
 required: _$1(in method foo)
       class C { def foo(a: Array[_ <: A]) { a(0) = a(1) }}

I think I understand; is it because there's no guarantee that all elements of "A" are the same type? Is there anyway to make this work, or am I just doing something janky?

4

1 回答 1

4

Maybe you mean

class C { def foo[T <: A](a: Array[T]) { a(0) = a(1) } }

?

This will let foo operate on arrays of A or its descendants, and it will maintain the type (so if you have it typed as B only, it'll stay that way).

于 2013-03-30T19:57:53.973 回答