Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors in scala with varargs

I am a Scala newbie. I've ploughed through a couple of books, and read some online tutorials. My first project is having problems, so I have reduced the code to the simplest thing that can go wrong.

I've searched google and stack overflow for scala/constructors/varargs, and read a couple of tours of scala.

The (nearly) simplest code is:

class Foo(val params: Int*)
case class Foo1(val p: Int) extends Foo(p)
case class Foo2(val p1: Int, val p2: Int) extends Foo(p1, p2)

object Demo extends App {
  override def main(args: Array[String]) {
    val f = Foo2(1, 2)
    f.p1
  }
}

The exception occurs when accessing p1 and is

Exception in thread "main" java.lang.ClassCastException: scala.collection.mutable.WrappedArray$ofInt cannot be cast to java.lang.Integer

Resorting to debugging using eclipse, I found an interesting property: When looking at variables

f   Foo2  (id=23)   
    p2  2   
    params  WrappedArray$ofInt  (id=33) 
        array    (id=81)    
            [0] 1   
            [1] 2   

So what happened to p1?

I'm sorry for troubling you with a newbie question

like image 640
Stave Escura Avatar asked Apr 30 '13 07:04

Stave Escura


2 Answers

You are not wrong but the compiler is. It tries to get p1 out of p (in your case it would try to get Foo2.p1 out of Foo.params):

def p1(): Int = scala.Int.unbox(Main$$anon$1$B.super.p());

which is obviously a bug because it can't work. Instead it should assign p1 in the ctor of the subclass.

I reported a bug: SI-7436.

like image 146
kiritsuku Avatar answered Sep 20 '22 10:09

kiritsuku


I cannot explain to you /why/ Scala gets confused, but the following works:

class Foo(p: Int, ps: Int*)
case class Foo1(p1: Int) extends Foo(p1)
case class Foo2(p1: Int, p2: Int) extends Foo(p1, p2)

object Main extends App {
  println( Foo1(1) )
  println( Foo2(2, 3) )
}

Also note that, when extending App, you wouldn't want to override main.

like image 40
fotNelton Avatar answered Sep 19 '22 10:09

fotNelton