As I mentioned in the question,
How can I use coalescing operator in Haxe?
Haxe does not have a null coalescing operator like C#'s ??.
That being said, it's possible to achieve something similar with macros. It looks like somebody has already written a library that does exactly this a few years ago. Here's an example from its readme:
var s = Sys.args()[0];
var path = s || '/default/path/to/../';
It uses the existing || operator because macros can not introduce entirely new syntax.
However, personally I would probably prefer a static extension like this:
class StaticExtensions {
public static function or<T>(value:T, defaultValue:T):T {
return value == null ? defaultValue : value;
}
}
using StaticExtensions;
class Main {
static public function main() {
var foo:String = null;
trace(foo.or("bar")); // bar
}
}
Instead of making your own, you could also consider using the safety library, which has a number of additional static extensions for Null<T> and features for dealing with null in general.
Use this addon:
https://github.com/skial/nco
Then, type
var value = a || 'backup value';
instead of
var value = (a == null) ? 'backup value' : a;
You can also utilize abstracts instead of macros for this purpose
class Test {
static function main() {
trace("Haxe is great!");
var s:Ory<String> = "hi!";
trace(s || "I don't get picked");
s = null;
trace(s || "I get picked");
trace(s + "!");
}
}
#:forward abstract Ory<T>(T) from T to T {
#:op(a||b) public inline function or(b:T):Ory<T> {
return this != null ? this : b;
}
}
Related
Is there possibility to compose multiple projections? Is it best approach for my use case?
I have these projections for CarInBazar class for example:
SimpleCarInList
WidgetForHotSale
NumberOfItemViews
FullCarData
CarMainImage
CarMainImageIconSize
CarAdditionalImages
And frontend is now making some UI page, which requires some of these projections.
Should I do:
frontend will do multiple requests for same resource with different projections
Implement Projection for each screen of frontend (duplicating things like NumberOfItemViews calculation,...)
Use inheritance and make specific projections utilizing extends keyword. i.e.:
#Projection(name = "screen-dashboardHome", types = {CarInBazar.class})
public interface DashboardHomeProjectionForCarInBazar extends SimpleCarInList,
WidgetForHotSale, CarMainImageIconSize {
}
Is there any possibility to request more projections at once? It could be than rendered in UI using provided profiles perhaps.
EDIT: as requested, providing projection definition example:
import org.springframework.data.rest.core.config.Projection;
import java.awt.*;
import java.util.Date;
#Projection(name = "CarMainImage", types = {CarInBazar.class})
public interface CarMainImage {
Date getLastUpdateDate();
Image getMainImage();
default String getMainImageAdditionalInformation() {
final var updated = this.getLastUpdateDate().getTime();
final var created = this.getCreatedAtDate().getTime();
if (created >= (updated - 10 minutes)) {
return "some business logic on not published fields";
} else {
return "could happen not only in spel";
}
}
}
Many projections does not contain any business logic and are only filtering fields.
Using multiple projections seems to not be supported (or widely supported or easy). Using suggestion from #Aivaras comment I have used this approach:
Repository code with custom JPQL query:
#Repository
#RepositoryRestResource
#Transactional(readOnly = true)
public interface SomeRepository extends PagingAndSortingRepository<Some, Long> {
Page<Some> findByNameContaining(String namePart, Pageable pageable);
#Query("select new sk.qpp.documents.projections.SomeCustomViewByQuery(s.name, s.startDate, s.endDate, s.goLiveDate, 42) from Some s where s.id = :id")
Optional<SomeCustomViewByQuery> getByIdProjectedForSpecialScreen(Long id);
}
And class SomeCustomViewByQuery is just simple DTO like thing. Using lombok it can look like:
#Value
public class SomeCustomViewByQuery {
private String name;
private Date startDate;
private Date endDate;
private Date goLiveDate;
// TODO make SomeHealth to be enum and specific logic behind it.
String getSomeHealth() {
final var start = this.getStartDate().getTime();
final var end = this.getEndDate().getTime();
final var goLive = this.getGoLiveDate().getTime();
final var now = System.currentTimeMillis();
if (now < start) {
return "not started yet";
} else {
if (now < end) {
return "work in progress";
} else {
if (now < goLive) {
return "passed end, but before goLive";
} else {
return "something after goLive time";
}
}
}
}
private int unicornsCount;
}
This way, I can make hand-crafted query (JQPL) and also create custom DTO instance. It is handy, where I need to do some joins to other tables with aggregation (count, avg, max, min, ...) and other things, which are better done on database side.
Note that I have already checked out this question, but the answers to it do not seem to be correct.
If I wanted to have private methods in regular JavaScript (which the answers suggest is not possible), I'd do something like this:
function myThing() {
var thingConstructor = function(someParam) {
this.publicFn(foo) {
return privateFn(foo);
}
function privateFn(foo) {
return 'called private fn with ' + foo;
}
}
}
var theThing = new myThing('param');
var result = theThing.publicFn('Hi');//should be 'called private fn with Hi'
result = theThing.privateFn; //should error
I'm trying to figure out what the syntax is to encapsulate the private function in TypeScript. If it turns out you can't, that's fine, but given that the answers in that older question incorrectly state that you can't create private methods in ordinary JavaScript, I am unwilling to just take those answers as authoritative.
So, it turns out it's just as simple as marking the method private. The thing I was missing is to be able to use the method is you need to use the this keyword.
So
export class myThing {
constructor(){}
publicFn(foo) {
return this.privateFn(foo);
}
private privateFn(foo) {
return 'called private fn with ' + foo;
}
}
I would like to extend the String type in Typescript.
Here's my code :
export class Str extends String{
constructor(str: string) {
super(str);
}
}
The problem is, after the call of the String constructor using super(str), the value of my new type stills empty.
I have the same problem with another type extending the native Array type.
Your code is transpiled to:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Str = (function (_super) {
__extends(Str, _super);
function Str(str) {
_super.call(this, str);
}
return Str;
})(String);
And the problem is that you no longer deal with the original native type that has special properties (like + operator on two strings). So your extended type - even if you would have succeded - would be severely limited and confusing for others.
Details and gotchas can be found Axel Rauschmayer's article: http://www.2ality.com/2013/03/subclassing-builtins-es6.html
Dart specification states:
Reified type information reflects the types of objects at runtime and may always be queried by dynamic typechecking constructs (the
analogs of instanceOf, casts, typecase etc. in other languages).
Sounds great, but there is no instanceof-like operator. So how do we perform runtime type-checking in Dart? Is it possible at all?
The instanceof-operator is called is in Dart. The spec isn't exactly friendly to a casual reader, so the best description right now seems to be http://www.dartlang.org/articles/optional-types/.
Here's an example:
class Foo { }
main() {
var foo = new Foo();
if (foo is Foo) {
print("it's a foo!");
}
}
Dart Object type has a runtimeType instance member (source is from dart-sdk v1.14, don't know if it was available earlier)
class Object {
//...
external Type get runtimeType;
}
Usage:
Object o = 'foo';
assert(o.runtimeType == String);
As others have mentioned, Dart's is operator is the equivalent of Javascript's instanceof operator. However, I haven't found a direct analogue of the typeof operator in Dart.
Thankfully the dart:mirrors reflection API has recently been added to the SDK, and is now available for download in the latest Editor+SDK package. Here's a short demo:
import 'dart:mirrors';
getTypeName(dynamic obj) {
return reflect(obj).type.reflectedType.toString();
}
void main() {
var val = "\"Dart is dynamically typed (with optional type annotations.)\"";
if (val is String) {
print("The value is a String, but I needed "
"to check with an explicit condition.");
}
var typeName = getTypeName(val);
print("\nThe mirrored type of the value is $typeName.");
}
There are two operators for type testing: E is T tests for E an instance of type T while E is! T tests for E not an instance of type T.
Note that E is Object is always true, and null is T is always false unless T===Object.
Exact type matching is done via runtimeType property. Checking if an instance or any of its parent types (in the inheritance chain) is of the given type is done via is operator:
class xxx {}
class yyy extends xxx {}
void main() {
var y = yyy();
print(y is xxx);
print(y.runtimeType == xxx);
}
Returns:
true
false
Simply use .runtimeType on the property like below,
print(unknownDataTypeProperty.runtimeType)
Just to clarify a bit the difference between is and runtimeType. As someone said already (and this was tested with Dart V2+) the following code:
class Foo {
#override
Type get runtimeType => String;
}
main() {
var foo = Foo();
if (foo is Foo) {
print("it's a foo!");
}
print("type is ${foo.runtimeType}");
}
will output:
it's a foo!
type is String
Which is wrong.
Now, I can't see the reason why one should do such a thing...
T is The type
print( T.runtimeType)
if(value is int ) Returns true if the type of the value is int,
else if(value is! int )
To check the type of a variable use runtimeType
void main() {
int a = 10;
print(a.runtimeType);
}
to check whether the type of a variable is the same as your expected use is or runtimeType
void main() {
int a = 10;
print(a.runtimeType == int); // true
//or
print(a is int); // true
}
print("enter your phone number:\n");
var phone number = stdin.readLineSync();
if(phone number.runtimeType is int == true) // checks if the values input are integers
{
print('you have successfully input your phone number!');
}
else{
print('only numbers are allowed');
}
On a project built with .NET 3.5, I am using LINQ expressions to dynamically generate code at runtime. The LINQ expressions are compiled using the Compile method and stored for later use as predicates with LINQ to objects.
The expressions are sometimes quite complicated and difficult to debug.
Below is an example of an expression viewed through the debugger visualizer in Visual Studio.
{request
=> (Invoke(workEnvelopeHead
=> (workEnvelopeHead.Method = value(Wombl.Scenarios.CannedResponses+<>c_DisplayClass58).pipeline),
request.WorkEnvelope.Head)
And Invoke(body =>
Invoke(value(Wombl.Scenarios.CannedResponses+<>c_DisplayClass78).isMatch,
body.SingleOrDefault()),Convert(request.WorkEnvelope.Body.Any)))}
I would like to be able to optimize expressions like the above so that the value(Wombl.Scenarios.CannedResponses+<>c__DisplayClass58).pipeline expression is replaced with a constant that is the variable's value.
In this particular case, value(Wombl.Scenarios.CannedResponses+<>c__DisplayClass58).pipeline is a reference in the lambda to a variable in the parent scope. Something like:
var pipeline = "[My variable's value here]";
// My lambda expression here, which references pipeline
// Func<RequestType, bool> predicate = request => ........ workEnvelopeHead.Method == pipeline ..........
The original expression, optimized ought to look like:
{request => (Invoke(workEnvelopeHead =>
(workEnvelopeHead.Method = "[My variable's value here]",
request.WorkEnvelope.Head) And Invoke(body => > Invoke(value(Wombl.Scenarios.CannedResponses+<>c__DisplayClass78).isMatch,
body.SingleOrDefault()),Convert(request.WorkEnvelope.Body.Any)))}
How can I make such optimizations at runtime to the LINQ expression, before compiling?
So I went ahead and wrote an expression visitor that replaces the variable references with the actual value. It wasn't so hard to do after all.
Usage:
var simplifiedExpression = ExpressionOptimizer.Simplify(complexExpression);
The class:
It inherits from ExpressionVisitor which came from the code samples on this page because in .NET 3.0 it is internal. In .NET 4.0 the class is public but might require some changes to this class.
public sealed class ExpressionOptimizer : ExpressionVisitor
{
private ExpressionOptimizer()
{
}
#region Methods
public static Expression<TDelegate> Simplify<TDelegate>(Expression<TDelegate> expression)
{
return expression == null
? null
: (Expression<TDelegate>) new ExpressionOptimizer().Visit(expression);
}
private static bool IsPrimitive(Type type)
{
return type.IsPrimitive
|| type.IsEnum
|| type == typeof (string)
|| type == typeof (DateTime)
|| type == typeof (TimeSpan)
|| type == typeof (DateTimeOffset)
|| type == typeof (Decimal)
|| typeof(Delegate).IsAssignableFrom(type);
}
protected override Expression VisitMemberAccess(MemberExpression memberExpression)
{
var constantExpression = memberExpression.Expression as ConstantExpression;
if (constantExpression == null || !IsPrimitive(memberExpression.Type))
return base.VisitMemberAccess(memberExpression);
// Replace the MemberExpression with a ConstantExpression
var constantValue = constantExpression.Value;
var propertyInfo = memberExpression.Member as PropertyInfo;
var value = propertyInfo == null
? ((FieldInfo) memberExpression.Member).GetValue(constantValue)
: propertyInfo.GetValue(constantValue, null);
return Expression.Constant(value);
}
#endregion
}