What is the `using` keyword in Haxe? - using

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

Related

How would you resolve a naming conflict inside dart?

Does dart have some sort of alias for naming conflicts like this?
library flutterfly;
import 'dart:ui';
class Color {
Color._();
// Color should be the class from dart:ui instead of itself.
static Color white() {
return Color(#FFFFFFFF);
}
}
Import the library with a namespace/prefix:
import 'dart:ui' as ui;
class Color {
Color._();
static ui.Color white() {
return ui.Color(0xFFFFFFFF);
}
}
That said, because whoever imports your flutterfly library can choose whatever library prefix they want (if any), adding your own Color class to use as a namespace isn't very useful, and its presence likely would cause conflicts for anything that uses it. Effective Dart recommends against classes that contain only static members. For this example, you could use top-level functions instead.

How can I apply the dependency inversion principle when using third party libraries?

I was reading about the dependency inversion principle and as far as I understand the relation is inverted because package A (high level) defines the interface and package B (low level) implements the interface, instead of directly invoking the class in package B.
But how can I apply the dependency inversion principle when I do not own package B? I'm using PHP and through the Composer package manager I import some third party libraries. Since I'm not in control of that code, I cannot make the classes in that library implement my high level interface.
I’ve searched on Google and Stackoverflow but i can’t seem to find questions or articles that mention this use-case.
The standard solution is to write an Adapter over the third-party library. In C#, it would look like the following:
public interface IFoo
{
void Bar(int baz);
string Qux(bool quux);
}
This interface would be defined in your A pakcage.
In another package, you'd reference the third-party library and write the Adapter:
public class ThirdPartyFoo : IFoo
{
private ThirdPartyObject thirdPartyObject;
// Class initialisation goes here...
public void Bar(int baz)
{
var corge = // perhaps translate or modify baz first...
thirdPartyObject.SomeMethod(corge);
}
public string Qux(bool quux)
{
var grault = // perhaps translate or modify quux first...
var res = thirdPartyObject.SomeOtherMethod(grault);
var garply = // perhaps translate res
return garply;
}
}

Are there any sealed classes alternatives in Dart 2.0?

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

How to use Namespaces in Swift?

The documentation only mentions nested types, but it's not clear if they can be used as namespaces. I haven't found any explicit mentioning of namespaces.
I would describe Swift's namespacing as aspirational; it's been given a lot of advertising that doesn't correspond to any meaningful reality on the ground.
For example, the WWDC videos state that if a framework you're importing has a class MyClass and your code has a class MyClass, those names do not conflict because "name mangling" gives them different internal names. In reality, however, they do conflict, in the sense that your own code's MyClass wins, and you can't specify "No no, I mean the MyClass in the framework" — saying TheFramework.MyClass doesn't work (the compiler knows what you mean, but it says it can't find such a class in the framework).
My experience is that Swift therefore is not namespaced in the slightest. In turning one of my apps from Objective-C to Swift, I created an embedded framework because it was so easy and cool to do. Importing the framework, however, imports all the Swift stuff in the framework - so presto, once again there is just one namespace and it's global. And there are no Swift headers so you can't hide any names.
EDIT: In seed 3, this feature is now starting to come online, in the following sense: if your main code contains MyClass and your framework MyFramework contains MyClass, the former overshadows the latter by default, but you can reach the one in the framework by using the syntax MyFramework.MyClass. Thus we do in fact have the rudiments of a distinct namespace!
EDIT 2: In seed 4, we now have access controls! Plus, in one of my apps I have an embedded framework and sure enough, everything was hidden by default and I had to expose all the bits of the public API explicitly. This is a big improvement.
Answered by SevenTenEleven in the Apple dev forum:
Namespaces are not per-file; they're per-target (based on the
"Product Module Name" build setting). So you'd end up with something
like this:
import FrameworkA
import FrameworkB
FrameworkA.foo()
All Swift declarations are considered to be part of
some module, so even when you say "NSLog" (yes, it still exists)
you're getting what Swift thinks of as "Foundation.NSLog".
Also Chris Lattner tweeted about namespacing.
Namespacing is implicit in Swift, all classes (etc) are implicitly
scoped by the module (Xcode target) they are in. no class prefixes
needed
Seems to be very different what I have been thinking.
While doing some experimentation with this I ended up creating these "namespaced" classes in their own files by extending the root "package". Not sure if this is against best practices or if it has any implications I'm mot aware of(?)
AppDelegate.swift
var n1 = PackageOne.Class(name: "Package 1 class")
var n2 = PackageTwo.Class(name: "Package 2 class")
println("Name 1: \(n1.name)")
println("Name 2: \(n2.name)")
PackageOne.swift
import Foundation
struct PackageOne {
}
PackageTwo.swift
import Foundation
struct PackageTwo {
}
PackageOneClass.swift
extension PackageOne {
class Class {
var name: String
init(name:String) {
self.name = name
}
}
}
PackageTwoClass.swift
extension PackageTwo {
class Class {
var name: String
init(name:String) {
self.name = name
}
}
}
Edit:
Just found out that creating "subpackages" in above code wont work if using separate files. Maybe someone can hint on why that would be the case?
Adding following files to the above:
PackageOneSubPackage.swift
import Foundation
extension PackageOne {
struct SubPackage {
}
}
PackageOneSubPackageClass.swift
extension PackageOne.SubPackage {
class Class {
var name: String
init(name:String) {
self.name = name
}
}
}
Its throwing a compiler error:
'SubPackage' is not a member type of 'PackageOne'
If I move the code from PackageOneSubPackageClass.swift to PackageOneSubPackage.swift it works. Anyone?
Edit 2:
Fiddling around with this still and found out (in Xcode 6.1 beta 2) that by defining the packages in one file they can be extended in separate files:
public struct Package {
public struct SubPackage {
public struct SubPackageOne {
}
public struct SubPackageTwo {
}
}
}
Here are my files in a gist:
https://gist.github.com/mikajauhonen/d4b3e517122ad6a132b8
I believe this is achieved using:
struct Foo
{
class Bar
{
}
}
Then it can be accessed using:
var dds = Foo.Bar();
Namespaces are useful when you need to define class with the same name as class in existing framework.
Suppose your app has MyApp name, and you need to declare your custom UICollectionViewController.
You don't need to prefix and subclass like this:
class MAUICollectionViewController: UICollectionViewController {}
Do it like this:
class UICollectionViewController {} //no error "invalid redeclaration o..."
Why?. Because what you've declared is declared in current module, which is your current target. And UICollectionViewController from UIKit is declared in UIKit module.
How to use it within current module?
var customController = UICollectionViewController() //your custom class
var uikitController = UIKit.UICollectionViewController() //class from UIKit
How to distinguish them from another module?
var customController = MyApp.UICollectionViewController() //your custom class
var uikitController = UIKit.UICollectionViewController() //class from UIKit
Swift uses modules much like in python (see here and here) and as #Kevin Sylvestre suggested you can also use the nested types as namespaces.
And to extend the answer from #Daniel A. White, in WWDC they were talking about the modules in swift.
Also here is explained:
Inferred types make code cleaner and less prone to mistakes, while
modules eliminate headers and provide namespaces.
You can use extension to use the mentioned structs approach for namespacing without having to indent all of your code towards the right. I've been toying with this a bit and I'm not sure I'd go as far as creating Controllers and Views namespaces like in the example below, but it does illustrate how far it can go:
Profiles.swift:
// Define the namespaces
struct Profiles {
struct Views {}
struct ViewControllers {}
}
Profiles/ViewControllers/Edit.swift
// Define your new class within its namespace
extension Profiles.ViewControllers {
class Edit: UIViewController {}
}
// Extend your new class to avoid the extra whitespace on the left
extension Profiles.ViewControllers.Edit {
override func viewDidLoad() {
// Do some stuff
}
}
Profiles/Views/Edit.swift
extension Profiles.Views {
class Edit: UIView {}
}
extension Profiles.Views.Edit {
override func drawRect(rect: CGRect) {
// Do some stuff
}
}
I haven't used this in an app since I haven't needed this level of separation yet but I think it's an interesting idea. This removes the need for even class suffixes such as the ubiquitous *ViewController suffix which is annoyingly long.
However, it doesn't shorten anything when it's referenced such as in method parameters like this:
class MyClass {
func doSomethingWith(viewController: Profiles.ViewControllers.Edit) {
// secret sauce
}
}
Even though it is possible to implement namespaces using Framework and Libraries but the best solution is to use local packages using Swift Package Manager. Besides having access modifiers, this approach has some other benefits. As in Swift Package Manager, the files are managed based on the directory system, not their target member ship, you won't have to struggle with merge conflicts that arise frequently in teamworks. Furthermore, there is no need to set file memberships.
To check how to use local Swift packages refer to the following link:
Organizing Your Code with Local Packages
In case anyone was curious, as of June 10th 2014, this is a known bug in Swift:
From SevenTenEleven
"Known bug, sorry! rdar://problem/17127940 Qualifying Swift types by their module name doesn't work."

It is planned in Dart language adding functionality to declaring closures (without using typedef) as typed functions?

Closures in Dart language used very often because they very powerful.
I want ask question about closures usability.
Assume this source code:
class SomeWork<T> {
Function _test;
SomeWork(bool test(T a, T b)) {
_test = test;
}
}
If I rewrote this code as this code fragment then the function (as an argument) will be untyped (or rather will have a different type).
class SomeWork<T> {
final Function test;
SomeWork(this.test) {
}
}
Question:
It is planned in Dart language adding functionality to declaring closures (without using typedef, "on the fly") as typed functions?
Like this example of code:
class SomeWork<T> {
final Function<bool, T, T> test;
SomeWork(this.test) {
}
}
P.S.
For clarification I want add (after a while) this example in C# language because as I understand given example in the Dart language perceived not entirely correct.
class SomeWork<T> {
sealed Func<T, T, bool> m_test;
SomeWork(Func<T, T, bool> test)
{
m_test = test;
}
}
I.e. I asked about about possibility using types similar to C# Func<> and Action<>.
No, there are no plans here that I know of. Early in Dart's development, there were a number of discussions about this unfortunate corner of the type annotation syntax, but the language designers feel it's a worthwhile trade-off in order to have type annotations that look familiar to programmers coming from C, C++, Java, and C#.

Resources