本文介绍了关于Scala泛型:无法找到元素类型T的类清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  def reverse [T](a:Array [T]):Array [T (a  val b = new Array [T](a.length)
(i b(i)= a(a.length - i - 1)
b
}

我收到error:can not find

有没有办法解决这个问题?

解决方案

只需添加一个上下文绑定给你的方法声明:

$ pre $ def $ reverse def [T:ClassManifest](a:Array [T]):Array [T] = ...

为了构造一个数组,数组的具体类型必须在编译时已知。此类型由编译器通过隐式ClassManifest参数提供。也就是说,Array构造函数的签名实际上是
$ b $ pre $ Array [T](size:Int)(隐式m:ClassManifest [ T]):Array [T]

为了提供这个参数,必须有一个ClassManifest当调用Array构造函数时的范围。因此,您的逆向方法还必须采用隐式的ClassManifest参数:

  def reverse [T](a:Array [T]) (隐式m:ClassManifest [T]):Array [T] = ... 
//或等价地
def reverse [T:ClassManifest](a:Array [T]):Array [T] = ...

后者简单的符号称为。


For a function as below:

def reverse[T](a: Array[T]): Array[T] = {
    val b = new Array[T](a.length)
    for (i <- 0 until a.length)
        b(i) = a(a.length -i - 1)
    b
}

I am getting "error: cannot find class manifest for element type T" from line 2.

Is there anyway to solve this?

解决方案

Simply add a context bound ClassManifest to your method declaration:

def reverse[T : ClassManifest](a: Array[T]): Array[T] = ...

In order to construct an array, the array's concrete type must be known at compile time. This type is supplied by the compiler via an implicit ClassManifest parameter. That is, the signature of the Array constructor is actually

Array[T](size: Int)(implicit m: ClassManifest[T]): Array[T]

In order to supply this parameter, there must be a ClassManifest in scope when the Array constructor is invoked. Therefore, your reverse method must also take an implicit ClassManifest parameter:

def reverse[T](a: Array[T])(implicit m: ClassManifest[T]): Array[T] = ...
// or equivalently
def reverse[T : ClassManifest](a: Array[T]): Array[T] = ...

The latter, simpler notation is called a context bound.

这篇关于关于Scala泛型:无法找到元素类型T的类清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:15