user972946
user972946

Reputation:

How to translate the following class definition from Java to Scala?

I am learning Scala and I cannot figure out how to translate the following Java code into Scala:

class Parent {
  Parent(int i) {}
}
public class Test extends Parent {
  final static int I = 1;
  Test() {
    super(I);
  }
}

Please help me, thanks.

Here are my failed attempts:

1.

class Parent(val i: Int) {}
object Test {
  val I = 1
}
class Test extends Parent(I) {
}

2.

class Parent(val i: Int) {}
class Test extends Parent(I) {
  val I = 1
}

Upvotes: 0

Views: 123

Answers (1)

dhg
dhg

Reputation: 52691

class Parent(i: Int)

class Test extends Parent(Test.I)  // `super` is done in the parent's constructor

object Test {
  val I = 1                        // `static` members go in an `object`
}

Note:

  1. You don't actually need the empty braces.
  2. Only declare i with val if you want it to be publicly accessible (but not modifiable). It's private by default.

Upvotes: 2

Related Questions