Are there any sealed classes alternatives in Dart 2.0? - dart

I have Android development background and I'm learning Flutter.
In Android it's a common practice to use Kotlin sealed classes to return a state from ViewModel e.g.
sealed class MyState {
data class Success(val data: List<MyObject>) : MyState()
data class Error(val error: String) : MyState()
}
I want to use similar pattern in Flutter and return a State object from the BLOC class. What is the best way to achieve the same in Flutter?

Such use case would be done using named factory constructors.
It requires a lot more code, but the behavior is the same.
class MyState {
MyState._();
factory MyState.success(String foo) = MySuccessState;
factory MyState.error(String foo) = MyErrorState;
}
class MyErrorState extends MyState {
MyErrorState(this.msg): super._();
final String msg;
}
class MySuccessState extends MyState {
MySuccessState(this.value): super._();
final String value;
}

RĂ©mi Rousselet's answer is somehow correct but as sindrenm mentioned:
Unfortunately, this isn't the same thing. Kotlin sealed classes guarantee that there are no other implementations of the given class outside of the file they're defined in. That means you can exhaust when statements (switch in Dart) by just providing all possible alternatives as cases, not having to think about potential sub-classes elsewhere
While there is an active discussion about this feature on dart language: Algebraic Data Types, but there is some libraries that can help you implement this behavior. You can use this libraries:
Sealed Unions
Super Enum
Sealed Class
And if you are using BLoC library you can use this lib:
Sealed Flutter Bloc
I hope that dart language add this feature ASAP

Soon Dart is going to support sealed classes.
GitHub Code: source
sealed class Either {}
class Left extends Either {}
class Right extends Either {}
You can now test the sealed class
test(Either either) {
switch (either) {
case Left(): print('Left');
case Right(): print('Right');
}
}

Here is the package for the Sealed Classes/Unions in Flutter
Freezed
This Package provided the features to deal with Data Classes, Sealed Class in Dart/Flutter
Here is the link which explains the beast use of freezed package in Flutter
Use of Freezed Package in Flutter/Dart

Related

TreeShakeable Providers in Angular 6 and Injector

Angular 6 has introduced tree shakeable providers with the
#Inject({provideIn:'...'}
syntax.
In order to take advantage of the tree shaking aspect, does it make a difference whether I inject the service directly via the constructor or via an Injector?
Example:
Sevice:
#Inject({provideIn:'...'}
class MyService {}
Consumer1:
#Component()
class MyComponent {
constructor(s: MyService) {}
}
Consumer2:
#Component()
class MyComponent {
constructor(#Inject(Injector) aInjector: Injector) {
const s: MyService = aInjector.get(MyService);
}
}
In both cases MyService gets injected. I would expect that only in the first case the AOT compiler will be able to determine that the service is used via static analysis.
What would be the effect if I used the second version? Would AOT detect the injection of Injector and then basically skip tree shaking for providers? Or is it smart enough to detect that MyService is fetched from the injector?

Guice Binding from Consumer Package

I am newbie for Guice and seeking help for the following use case :
I have developed one package say (PCKG) where the entry class of that package depends on other class like:
A : Entry point class --> #Inject A(B b) {}
B in turn is dependent on C and D like --> #Inject B(C c, D d) {}
In my binding module I am doing :
bind(BInterface).to(Bimpl);
bind(CInterface).to(CImpl);
...
Note I am not providing binding information for A as i want to provide its binding by its consumer class. (this is how the design is so my request is to keep the discussion on main problem rather than design).
Now my consumer class is doing like:
AModule extends PrivateModule {
protected void configure() {
bind(AInterface.class).annotatedWith(AImpl.class);
}
}
Also in my consumer package:
.(new PCKGModule(), new AModule())
Q1. Am i doing the bindings correctly in consumer class. I am confused because when i am doing some internal testing as below in my consumer package:
class testModule {
bind(BInterface).to(Bimpl);
bind(CInterface).to(CImpl)...
}
class TestApp {
public static void main(..) {
Guice.createInstance(new testModule());
Injector inj = Guice.createInstance(new AModule());
A obj = inj.getInstance(A.class);
}
}
It is throwing Guice creation exception.Please help me get rid of this situation.
Also one of my friend who is also naive to Guice was suggesting that I need to create B's instance in AModule using Provides annotation. But i really didn't get his point.
Your main method should look like this:
class TestApp {
public static void main(..) {
Injector injector = Guice.createInjector(new TestModule(), new AModule());
A obj = injector.getInstance(A.class);
}
Note that the Java convention is for class names to have the first letter capitalised.
I'm pretty sure your implementation of AModule isn't doing what you think it's doing either, but it's hard to be certain based on the information you've provided. Most likely, you mean to do this:
bind(AInterface.class).to(AImpl.class)`
There's no need to do anything "special" with A's binding. Guice resolves all the recursion for you. That's part of its "magic".
annotatedWith() is used together with to() or toInstance(), like this:
bind(AInterface.class).to(AImpl.class).annotatedWIth(Foo.class);
bind(AInterface.class).to(ZImpl.class).annotatedWIth(Bar.class);
Then you can inject different implementations by annotating your injection points, e.g.:
#Inject
MyInjectionPoint(#Foo AInterface getsAImpl, #Bar AInterface getsZImpl) {
....
}
It's worth also pointing out that you can potentially save yourself some boilerplate by not bothering with the binding modules (depending how your code is arranged) and using JIT bindings:
#ImplementedBy(AImpl.class)
public interface AInterface {
....
}
These effectively act as "defaults" which are overridden by explicit bindings, if they exist.

What is the purpose of the getter methods in Components in Dagger 2?

I am trying to understand Components in Dagger 2. Here is an example:
#Component(modules = { MyModule.class })
public interface MyComponent {
void inject(InjectionSite injectionSite);
Foo foo();
Bar bar();
}
I understand what the void inject() methods do. But I don't understand what the other Foo foo() getter methods do. What is the purpose of these other methods?
Usage in dependent components
In the context of a hierarchy of dependent components, such as in this example, provision methods such as Foo foo() are for exposing bindings to a dependent component. "Expose" means "make available" or even "publish". Note that the name of the method itself is actually irrelevant. Some programmers choose to name these methods Foo exposeFoo() to make the method name reflect its purpose.
Explanation:
When you write a component in Dagger 2, you group together modules containing #Provides methods. These #Provides methods can be thought of as "bindings" in that they associate an abstraction (e.g., a type) with a concrete way of resolving that type. With that in mind, the Foo foo() methods make the Component able to expose its binding for Foo to dependent components.
Example:
Let's say Foo is an application Singleton and we want to use it as a dependency for instances of DependsOnFoo but inside a component with narrower scope. If we write a naive #Provides method inside one of the modules of MyDependentComponent then we will get a new instance. Instead, we can write this:
#PerFragment
#Component(dependencies = {MyComponent.class }
modules = { MyDependentModule.class })
public class MyDependentComponent {
void inject(MyFragment frag);
}
And the module:
#Module
public class MyDepedentModule {
#Provides
#PerFragment
DependsOnFoo dependsOnFoo(Foo foo) {
return new DependsOnFoo(foo);
}
}
Assume also that the injection site for DependentComponent contains DependsOnFoo:
public class MyFragment extends Fragment {
#Inject DependsOnFoo dependsOnFoo
}
Note that MyDependentComponent only knows about the module MyDependentModule. Through that module, it knows it can provide DependsOnFoo using an instance of Foo, but it doesn't know how to provide Foo by itself. This happens despite MyDependentComponent being a dependent component of MyComponent. The Foo foo() method in MyComponent allows the dependent component MyDependentComponent to use MyComponent's binding for Foo to inject DependsOnFoo. Without this Foo foo() method, the compilation will fail.
Usage to resolve a binding
Let's say we would like to obtain instances of Foo without having to call inject(this). The Foo foo() method inside the component will allow this much the same way you can call getInstance() with Guice's Injector or Castle Windsor's Resolve. The illustration is as below:
public void fooConsumer() {
DaggerMyComponent component = DaggerMyComponent.builder.build();
Foo foo = component.foo();
}
Dagger is a way of wiring up graphs of objects and their dependencies. As an alternative to calling constructors directly, you obtain instances by requesting them from Dagger, or by supplying an object that you'd like to have injected with Dagger-created instances.
Let's make a coffee shop, that depends on a Provider<Coffee> and a CashRegister. Assume that you have those wired up within a module (maybe to LightRoastCoffee and DefaultCashRegister implementations).
public class CoffeeShop {
private final Provider<Coffee> coffeeProvider;
private final CashRegister register;
#Inject
public CoffeeShop(Provider<Coffee> coffeeProvider, CashRegister register) {
this.coffeeProvider = coffeeProvider;
this.register = register;
}
public void serve(Person person) {
cashRegister.takeMoneyFrom(person);
person.accept(coffeeProvider.get());
}
}
Now you need to get an instance of that CoffeeShop, but it only has a two-parameter constructor with its dependencies. So how do you do that? Simple: You tell Dagger to make a factory method available on the Component instance it generates.
#Component(modules = {/* ... */})
public interface CoffeeShopComponent {
CoffeeShop getCoffeeShop();
void inject(CoffeeService serviceToInject); // to be discussed below
}
When you call getCoffeeShop, Dagger creates the Provider<Coffee> to supply LightRoastCoffee, creates the DefaultCashRegister, supplies them to the Coffeeshop constructor, and returns you the result. Congratulations, you are the proud owner of a fully-wired-up coffeeshop.
Now, all of this is an alternative to void injection methods, which take an already-created instance and inject into it:
public class CoffeeService extends SomeFrameworkService {
#Inject CoffeeShop coffeeShop;
#Override public void initialize() {
// Before injection, your coffeeShop field is null.
DaggerCoffeeShopComponent.create().inject(this);
// Dagger inspects CoffeeService at compile time, so at runtime it can reach
// in and set the fields.
}
#Override public void alternativeInitialize() {
// The above is equivalent to this, though:
coffeeShop = DaggerCoffeeShopComponent.create().getCoffeeShop();
}
}
So, there you have it: Two different styles, both of which give you access to fully-injected graphs of objects without listing or caring about exactly which dependencies they need. You can prefer one or the other, or prefer factory methods for the top-level and members injection for Android or Service use-cases, or any other sort of mix and match.
(Note: Beyond their use as entry points into your object graph, no-arg getters known as provision methods are also useful for exposing bindings for component dependencies, as David Rawson describes in the other answer.)

What is the `using` keyword in Haxe?

I often see people use the keyword using in their Haxe code. It seem to go after the import statements.
For example, I found this is a code snippet:
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
using haxe.macro.Tools;
using Lambda;
What does it do and how does it work?
The "using" mixin feature of Haxe is also referred as "static extension". It's a great syntactic sugar feature of Haxe; they can have a positive effect on code readability.
A static extension allows pseudo-extending existing types without modifying their source. In Haxe this is achieved by declaring a static method with a first argument of the extending type and then bringing the defining class into context through the using keyword.
Take a look at this example:
using Test.StringUtil;
class Test {
static public function main() {
// now possible with because of the `using`
trace("Haxe is great".getWordCount());
// otherwise you had to type
// trace(StringUtil.getWordCount("Haxe is great"));
}
}
class StringUtil {
public static inline function getWordCount(value:String) {
return value.split(" ").length;
}
}
Run this example here: http://try.haxe.org/#C96B7
More in the Haxe Documentation:
Haxe static extensions in the Haxe Manual
Haxe static extensions tagged articles in the Haxe Code Cookbook

Using #Inject with generic type

I've been searching here about it, but haven't found an answer.
In my application, I've an abstract main class for my controllers, with some methods and properties. And I want to inject the DAO automatically.
abstract class AbstractController<E extends AbstractEntity, D extends AbstractDAO<E>> {
#Inject
private D dao;
// getters and setters
}
abstract class AbstractDAO<E extends AbstractEntity> {
#PersistentContext
private EntityManager em;
// finds returns E
}
// implemenation/usage
class CarController extends AbstractController<Car, CarDAO> {
}
Getting the exception:
org.jboss.weld.exceptions.DefinitionException: WELD-001407 Cannot declare an injection point with a type variable: [field] #Inject private AbstractController.dao
Using: Glassfish 3.1 and JSF 2.1.
Is there a workaround or alternative for this?
Thanks.
It's technically very complicated for reflection to detect the proper runtime type by a generic declaration in the source and cast to it. Weld simply don't and won't support it.
Better declare it against AbstractDAO<E>:
private AbstractDAO<E> dao;
You gain nothing with declaring it against D anyway.

Resources