How to define a constructor without parameters in Scala

This question is so stupid ... Anyway, I just can’t find the information I need, because every class of the Scala -constructor class I see working with at least one parameter.

I want this class to translate 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 constructor without parameters. I confused Scala with this (), but I could not get a similar example similar to the one above. How can I write that in Scala?

+4
source share
2 answers

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") (...) } 
+11
source

@dbyrne reviewed the most important parts, but I will add a few additional details.

  • If the class has no parameters and is immutable, consider it as an object instead.
  • A constructor defined by class-level operators and parameter lists after the class name is known as the primary constructor. * Helper constructors * are defined by def this() = ... Unlike Java, each helper constructor must delegate the main constructor.
  • When you declare a primary constructor with zero parameter lists, the compiler automatically adds one empty parameter list. If you define a constructor with one implicit parameter list, the compiler will add an empty parameter list before that.
+4
source

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


All Articles