簡體   English   中英

在Scala中定義一個函數,該函數將通配符數組作為參數

[英]Define a function in Scala that takes an Array of a wildcard as a parameter

我有一個看似非常簡單的Scala問題,這使我發瘋。 這個:

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

不編譯。 它說:

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) }}

我想我明白; 是因為不能保證“ A”的所有元素都屬於同一類型? 反正有做這項工作的方法,還是我只是在做一些簡陋的事情?

也許你是說

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

這將使foo在A或其后代的數組上進行操作,並保持類型(因此,如果僅將其鍵入為B ,它將保持這種狀態)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM