4

This question is so stupid... Anyway, i just can't find the right information, because every Scala-constructor example class i see works with at least one parameter.

I want to have this class translated from Java to Scala:

public class SubscriptionConverter extends Converter {
  public SubscriptionConverter() {
    Context ctx = new InitialContext();
    UserEJB userEJB = (UserEJB) ctx.lookup("java:global/teachernews/UserEJB");
  }
  (...)
}

So i only have a parameterless constructor. I messed around in Scala with this(), but i couldn't get a similar example like the one above working. How do i do i write that in Scala?

2 Answers 2

11

Any statements declared at the class level are executed as part of the default constructor. So you just need to do something like this:

class SubscriptionConverter extends Converter {
  val ctx = new InitialContext
  val userEJB = ctx.lookup("java:global/teachernews/UserEJB")
  (...)
}
Sign up to request clarification or add additional context in comments.

4 Comments

And you'll probably want to declare those vals private -- otherwise they'll be public fields.
Note that the above example does not produce the same effect as the code in the question. In that code, the variables are local to the scope of the method, while here they get into every instance of the object. Scala 2.8's locally might be used here to introduce a block.
@Daniel where can i read more about locally? Couldn't find any information, not even in the 2.8 language reference
@ifischer locally is defined on scala.Predef, and it really doesn't do anything. It's just something to make dangling blocks (nested blocks) look better.
4

@dbyrne has covered the most important parts, but I'll add a few side details.

  1. If a class has no parameters, and it's immutable, consider declare it as an object instead.
  2. The constructor defined by statements at the class level and by parameter lists after the class name is known as the primary constructor. * Auxiliary constructors* are defined by def this() = .... Unlike Java, each auxiliary constructor must delegate to the primary constructor.
  3. When you declare a primary constructor with zero parameter lists, the compiler will automatically add a single, empty parameter list. If you define a constructor with one implicit parameter list, the compiler will add an empty parameter list before this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.