Define new Variable of Type in Javascript EMCA Script (Please give me a short hint how to shorten the code)

Hi,

I’ve just tried to translate a script from DSL to Javascript EMCA Script,
Somehow it’s very confusing to me that i cannot simply set a type without Java.Type("").
Can someone please help me how this can be done?
I’ve already took a look to Blocky but I guess creating a variable of type is not possible.

Can someone tell me if the script below can be written in an easier notation?

Sorry
/Franz

var home_location = Java.type("org.openhab.core.library.types.PointType");
var home_lat = Java.type("org.openhab.core.library.types.DecimalType");
var home_long = Java.type("org.openhab.core.library.types.DecimalType");

home_lat = new home_lat(49.0007495);
home_long = new home_long(12.0779579);
home_location = new home_location(home_lat, home_long);

phone_location = itemRegistry.getItem("FJSIphonePingableNetworkDevice_Location").getStateAs(PointType.class);

var distance = phone_location.distanceFrom(home_location).intValue();

events.postUpdate("DistanceFromHome", distance);

The script is running in the programming language JavaScript.

openHAB is written in the language Java.

They are completely different programming languages. In order to use a Java something in JavaScript it needs to be translated from Java to JavaScript.

That’s what Java.type does. It’s like those import statements you’ve seen in Rules DSL code, only it’s importing and translating.

Assuming you are using Nashorn and not the GraalVM add-on, a bunch of stuff is in fact “imported” for you including all the Item and State types.

So you don’t need to do the Java.type yourself.

home_lat = new DecimalType(49.0007495);
home_long = new DecimalType(12.0779579);
home_location = new PointType(home_lat, home_long);

...

But if you did, by chance, have to import something to use it, such as ZonedDateTime, you only do it once.

var ZonedDateTime = Java.type("java.time.ZonedDateTime");

var now = ZonedDateTime.now();
var yesterday = ZonedDateTime.now().minusDays(1);

var Duration = Java.type("java.time.Duration");
var between = new Duration(yesterday, now);
1 Like

Hi @rlkoshak,

thank you so much this really helped me to understand the whole construction in a better way!

Have a good weekend!
/Franz

Hi @rlkoshak,

Thanks again for that explanation.
Just one more question on that.
Is it normal that I cannot see these Datatypes work the intelisense in the Webfrontend rules editor?

Thx
/Franz

JavaScript is a weakly typed language. Intellisense doesn’t usually work very well with it because you don’t actually know the types of things until runtime.

1 Like