6

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

4

3 回答 3

6

你没有错,但编译器错了。它试图p1摆脱p(在你的情况下它会尝试Foo2.p1摆脱Foo.params):

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

这显然是一个错误,因为它无法工作。相反,它应该p1在子类的ctor中分配。

我报告了一个错误:SI-7436

于 2013-04-30T09:14:08.550 回答
1

我无法向您解释 /why/ Scala 会感到困惑,但以下方法有效:

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

另请注意,在扩展 时App,您不想覆盖main.

于 2013-04-30T08:11:37.053 回答
0

您应该看一下此评论及其上方的答案,我认为它应该回答您的问题;-)

于 2013-04-30T08:35:32.567 回答