How to perform runtime type checking in Dart? - dynamic

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');
}

Related

How can I use coalescing operator in Haxe?

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;
}
}

How to create a static pointer variable to itself in Swift?

In Objective-C I often use the pattern of using a static void* as an identification tag. At times these tags are only used within that function/method, hence it's convenient to place the variable inside the function.
For example:
MyObscureObject* GetSomeObscureProperty(id obj) {
static void* const ObscurePropertyTag = &ObscurePropertyTag;
MyObscureObject* propValue = objc_getAssociatedObject(id,ObscurePropertyTag);
if(!propValue) {
propValue = ... // lazy-instantiate property
objc_setAssociatedObject(obj,ObscurePropertyTag,propValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return propValue;
}
The question is, how to write the ObscurePropertyTag private-constant-pointer-to-itself in Swift? (Preferrably 2.1 but future already-announced versions should be okay)
I've looked around and it seems that I have to put this ObscurePropertyTag as a member variable and there doesn't seem to be a way around it.
Unlike (Objective-)C, you cannot take the address of an
uninitialized variable in Swift. Therefore creating a self-referencing
pointer is a two-step process:
Swift 2:
var ptr : UnsafePointer<Void> = nil
withUnsafeMutablePointer(&ptr) { $0.memory = UnsafePointer($0) }
Swift 3:
var ptr = UnsafeRawPointer(bitPattern: 1)!
ptr = withUnsafePointer(to: &ptr) { UnsafeRawPointer($0) }
For your purpose, is it easier to use the address of a global variable with &, see for
example
Is there a way to set associated objects in Swift?.
If you want to restrict the scope of the "tag" to the function itself
then you can use a static variable inside a local struct. Example:
func obscureProperty(obj : AnyObject) -> MyObscureObject {
struct Tag {
static var ObscurePropertyTag : Int = 0
}
if let propValue = objc_getAssociatedObject(obj, &Tag.ObscurePropertyTag) as? MyObscureObject {
return propValue
}
let propValue = ... // lazy instantiate property value
objc_setAssociatedObject(obj, &Tag.ObscurePropertyTag,propValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return propValue
}
Try this:
var GetSomeObscureProperty: MyObscureObject = nil
withUnsafePointer(& GetSomeObscureProperty) {
GetSomeObscureProperty = MyObscureObject($0)
}
In short
let GetSomeObscureProperty = UnsafePointer<()>()

Extending String native type in Typescript

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

Type casting in C++\CLI project

I have project which I am compiling with /clr. I have a class like below..
ref class A
{
public:
void CheckValue(void * test);
typedef ref struct val
{
std::string *x;
}val_t;
};
in my implementation I ahve to use something like below..
void A::CheckValue(void *test)
{
a::val_t^ allVal = (a::val_t^)test;
}
in my main I have used like..
int main()
{
A^ obj = gcnew A();
a::val_t valObj = new std::string("Test");
obj->CheckValue((void*)valObj);
}
I am getting type cast error and two places -
obj->CheckValue((void*)valObj);
and at
obj->CheckValue((void*)valObj);
error C2440: 'type cast' : cannot convert from 'void*' to 'A::val_t ^'
This snippet is just to show behavior at my end and I ahve to use it this way only. Earlier I was running it using non /clr so it compiled fine.
Now question I have how can I make this type casting work in C++/CLI type project?
Replace void * with Object^. You can also write a generic version of CheckValue but then there is not much point of having a weak-typed parameter when you have the type in the generic parameter.
A reference handle represents an object on the managed heap. Unlike a native pointer, CLR could move the object around during a function call, so the behavior of a pointer and a reference handle is different, and a type cast would fail. You can also pin the object being referenced using pin_ptr if you really need a void* so CLR would not be moving the object during the function call.
Here is how I would get around the limitation you are seeing, just remove the struct from the managed object, since it contains native pointer types.
struct val_t
{
char* x;
};
ref class A
{
public:
void CheckValue(void* test);
};
void A::CheckValue(void* test)
{
val_t* allVal = (val_t*)test;
}
int main()
{
A^ obj = gcnew A();
val_t valObj;
valObj.x = "Test";
obj->CheckValue((void*)&valObj);
}
Now, if you absolutely need the struct to be managed, here is how to do it:
ref class A
{
public:
void CheckValue(void * test);
value struct val_t
{
char* x;
};
};
void A::CheckValue(void *test)
{
a::val_t* allVal = (a::val_t*)test;
}
int main()
{
A^ obj = gcnew A();
a::val_t valObj;
valObj.x = "Test";
pin_ptr<a::val_t> valPin = &valObj;
obj->CheckValue((void*)valPin);
}

how to parse non-string values in Opencsv HeaderColumnNameMappingStrategy

I'm using a HeaderColumnNameMappingStrategy to map a csv file with a header into a JavaBean. String values parse fine but any "true" or "false" value in csv doesn't map to JavaBean and I get the following exception from the PropertyDescriptor:
java.lang.IllegalArgumentException: argument type mismatch
The code where it occurs is in CsvToBean, line 64:
protected T processLine(MappingStrategy<T> mapper, String[] line) throws
IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException {
T bean = mapper.createBean();
for(int col = 0; col < line.length; col++) {
String value = line[col];
PropertyDescriptor prop = mapper.findDescriptor(col);
if (null != prop) {
Object obj = convertValue(value, prop);
// this is where exception is thrown for a "true" value in csv
prop.getWriteMethod().invoke(bean, new Object[] {obj});
}
}
return bean;
}
protected PropertyEditor getPropertyEditor(PropertyDescriptor desc) throws
InstantiationException, IllegalAccessException {
Class<?> cls = desc.getPropertyEditorClass();
if (null != cls) return (PropertyEditor) cls.newInstance();
return getPropertyEditorValue(desc.getPropertyType());
}
I can confirm (via debugger) that the setter method id correctly retrieved at this point.
The problem occurs in desc.getPropertyEditorClass() since it returns null. I assumed primitive types and its wrappers are supported. Are they not?
I've run into this same issue. The cleanest way is probably to override getPropertyEditor like pritam did above and return a custom PropertyEditor for your particular object. The quick and dirty way would be to override convertValue in anonymous class form, like this:
CsvToBean<MyClass> csvToBean = new CsvToBean<MyClass>(){
#Override
protected Object convertValue(String value, PropertyDescriptor prop) throws InstantiationException,IllegalAccessException {
if (prop.getName().equals("myWhatever")) {
// return an custom object based on the incoming value
return new MyWhatever((String)value);
}
return super.convertValue(value, prop);
}
};
This is working fine for me with OpenCSV 2.3. Good luck!
I resolved this by extending CsvToBean and adding my own PropertyEditors. Turns out opencsv just supports primitive types and no wrappers.
Pritam's answer is great and this is a sample for dealing with datetime format.
PropertyEditorManager.registerEditor(java.util.Date.class, DateEditor.class);
You should write your own editor class like this:
public class DateEditor extends PropertyEditorSupport{
public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
#Override
public void setAsText(String text){
setValue(sdf.parse(text));}
}