Constructors in scala with varargs

I am new to Scala. I went through a couple of books and read some online lessons. My first project has problems, so I reduced the code to the simplest thing that might go wrong.

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

The simplest code (almost):

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 } } 

An exception occurs when accessing p1 and

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

Resorting to debugging using eclipse, I found an interesting property: when viewing 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 apologize for the fact that you were worried about the newcomer.

+6
source share
3 answers

You are not mistaken, but the compiler. It tries to get p1 from p (in your case, it will try to get Foo2.p1 from Foo.params ):

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

which is obviously a mistake because it cannot work. Instead, it should assign p1 to the ctor of the subclass.

I reported an error: SI-7436 .

+6
source

I can’t 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 you expand the App you do not want to override main .

+1
source

You should take a look at this comment and answer a little higher, I think it should answer your problem; -)

0
source

Source: https://habr.com/ru/post/943941/


All Articles