Samik R
Samik R

Reputation: 1638

Additional constructor for a generic class with specific type

I have a generic class in Scala (2.11.8), which works fine. How can I add an additional constructor for a specific type?

Here is the original class definition, and my trial for adding the extra constructor.

class MyArray[T](name: String, array: Array[T])
{ 
  val myName = name
  val values = array

  override def toString = s"Name: $myName, Vals: [${values.mkString(", ")}]"

  def this(name: String, min: Int, max: Int) = this(name, (min to max).toArray.asInstanceOf[Array[T]])
}

In REPL, this is what I see:

scala> val a = new MyArray("a", Array(10,12))
a: MyArray[Int] = Name: a, Vals: [10, 12]

scala> val b = new MyArray("b", Array("test", "mytest"))
b: MyArray[String] = Name: b, Vals: [test, mytest]

scala> val c = new MyArray("c", 10, 15)
c: MyArray[Nothing] = Name: c, Vals: [10, 11, 12, 13, 14, 15]

How can I rewrite the constructor so that the output from the last line in REPL becomes MyArray[Int] = ...? I have tried the followings, and none of them work:

def this(name: String, min: Int, max: Int) = this[Int](name, (min to max).toArray.asInstanceOf[Array[T]])
<console>:1: error: ';' expected but '[' found.

def this(name: String, min: Int, max: Int) = this[Int](name, (min to max).toArray)
<console>:1: error: ';' expected but '[' found.

def this[T](name: String, min: Int, max: Int) = this(name, (min to max).toArray.asInstanceOf[Array[T]])
<console>:1: error: no type parameters allowed here 

def this(name: String, min: Int, max: Int) = MyArray[Int](name, (min to max).toArray)
<console>:1: error: 'this' expected but identifier found.

Thanks.

Upvotes: 0

Views: 52

Answers (1)

Jordan Cutler
Jordan Cutler

Reputation: 582

I'm not sure of the way to do what you're asking using the this constructor, but here's how you can do it with a companion object.

object MyArray {
  def apply[T](name: String, array: Array[T]): MyArray[T] = {
    new MyArray[T](name, array)
  }

  def apply(name: String, min: Int, max: Int): MyArray[Int] = {
    new MyArray[Int](name, (min to max).toArray)
  }
}

scala> val c = MyArray("c", 10, 15)
c: MyArray[Int] = Name: c, Vals: [10, 11, 12, 13, 14, 15]

Upvotes: 4

Related Questions