-
Notifications
You must be signed in to change notification settings - Fork 4
Companion Classes
In Scala you can define a companion object for a class, acting as a static reference/singleton for that class allowing you to define factory methods.
This behavior does not exist in Java but can be emulated by statically importing methods.
The primary purpose is to get the Scala feel of instantiating classes.
One use case is to define methods with the same name as the class and let these methods invoke the constructor thus creating a nice way to create instances without using the word "new". This can be achieved in java by statically importing a method and then using it. The limitation is that classes may not have method with the same name as the class itself hence new companion classes have to be created. To be able to use it in a neat concise way one needs to statically import the method. Example using the TryCompanion class.
import static javascalautils.TryCompanion.Failure;
import static javascalautils.TryCompanion.Success;
import static javascalautils.TryCompanion.Try;
Try<Integer> t = Try(() -> 9 / 3);
Try<String> ts = Success("Peter was here");
Try<String> tf = Failure(new Exception("Bad mojo!"));
The companion classes provided by the library are:
- EitherCompanion
- FutureCompanion
- OptionCompanion
- PromiseCompanion
- TryCompanion
Refer to the Java Doc for details.
- Introduction
- JavaDoc (Latest)
- Containers
- Option/Some/None
- Try/Success/Failure
- Either/Left/Right
- Asynchronous Execution
- Future/Promise
- Companion Classes
- The Unit Type
- Testing/Asserts
- License
- Chat room for the project:
- Continuous Integration: