简体   繁体   English

如何使用泛型类型数组和泛型类型类作为构造函数中的参数?

[英]How to work with generic type array and generic type class as parameter in constructor?

I want to convert the following simple java code into scala code. 我想将以下简单的Java代码转换为Scala代码。 I know T <: Comparable[T] will be used for T extends Comparable . 我知道T <: Comparable[T]将用于T extends Comparable For generic type array, I have to use either Manifest or ClassManifest but I could not convert the two constructors for scala code. 对于泛型类型数组,我必须使用ManifestClassManifest但无法将两个构造函数转换为Scala代码。

public class MyClass<T extends Comparable> {

    private static int MAX_SIZE = 40;
    private T[] array;
    private int count = 0;

    public MyClass(Class<T> clazz) {
        this(clazz, MAX_SIZE);
    }

    public MyClass(Class<T> clazz, int size) {
        array = (T[]) Array.newInstance(clazz, size);
    }
}

This is a rough sketch of what a Scala class would look like: 这是Scala类的大致示意图:

import scala.reflect.ClassTag

class MyClass[T : Ordered : ClassTag](size: Int) {
  val arr: Array[T] = new Array[T](size)

  def this() {
    this(40)
  }
}

Because of Scala auxiliary constructor initialization order, you can't access this inside the constructor (that is the reason I hard coded 40 instead of settings a max value field). 由于Scala辅助构造函数的初始化顺序,您无法在构造函数内部访问this代码(这就是我硬编码40而不是设置最大值字段的原因)。 If you want to get around that, you can define a companion object to MyClass with an apply method which takes no argument: 如果要解决此问题,可以使用不带参数的apply方法为MyClass定义一个伴随对象:

import scala.reflect.ClassTag

class MyClass[T : Ordered : ClassTag](size: Int) {
  val arr: Array[T] = new Array[T](size)
}

object MyClass {
  final val maxSize: Int = 40
  def apply[T : Ordered : ClassTag]() = new MyClass[T](maxSize)
}

And then utilize it like this: 然后像这样利用它:

val clz = MyClass[Int]()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM