【问题标题】:Define a function in Scala that takes an Array of a wildcard as a parameter在 Scala 中定义一个将通配符数组作为参数的函数
【发布时间】:2013-03-21 07:26:40
【问题描述】:

我有一个看似非常简单的 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”的所有元素都是同一类型吗?有没有办法让这项工作,或者我只是在做一些笨拙的事情?

【问题讨论】:

    标签: scala generics inheritance collections


    【解决方案1】:

    也许你的意思

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

    ?

    这将使 foo 对 A 或其后代的数组进行操作,并且它将保持类型(因此,如果您仅将其键入为 B,它将保持这种状态)。

    【讨论】:

    • 非常感谢您的帮助。这解决了这个问题,但问题实际上更深层次,问题是类似的,但我在这里发布一个新问题:stackoverflow.com/questions/15723338/…。如果您也能提供帮助,我将不胜感激。
    猜你喜欢
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    • 2017-12-03
    • 2016-08-26
    • 1970-01-01
    相关资源
    最近更新 更多