I am pretty new to programming so I am not sure what this is called but in Javascript, for example
arr[0].obj[0].getSomething();
can be shorten to
var o = arr[0].obj[0];
o.getSomething();
so that we do not have to repeat
arr[0].obj[0]
what is the equivalent of this in Java? I can't seem to find it.
Also tell me what should the title be, I am not sure whether my title is appropriate.
You do it just the same way:
If you have
House[] houses; // An array of houses
// initialize and fill the array
... and inside the House class you have a field doors:
public class House {
Door[] doors;
// Initialize the array in a constructor, add getter and setter methods
}
Then you can do either
Color doorColor = houses[0].doors[0].getColor();
or you store the door you want in a variable and then ask for its color:
Door door = houses[0].doors[0];
Color doorColor = door.getColor();
With the given snipped I can understand your java code would look like as below.
class A{
B obj[];
}
class B {
public void doSomething(){}
}
lets say you have array of A class object as as your code snippet says
arr[0].obj[0].getSomething();
in java it would be of class A like below
A arr[]
so the code would be
arr[0].obj[0].doSomething();
we can write it as
A firstA = arr[0];
B firstB = firstA.obj[0];
firstB.doSomething();
or
B firstB = arr[0].obj[0];
firstB.doSomething();
Related
I have class Movie. Movie constructor should provide a generation of unique product id within the application no matter how many products are created. You also need to define a field with the name of the movie. But according to the condition, for this I have to use Symbol data type. How can i do this?
class Movie {
constructor(name) {
//here I need to generate a unique id;
//here I need to define name fields
}
}
class Movie {
sym = Symbol('symbol description')
constructor(name) {
this.symInConstructor = Symbol('symbol description')
// this.sym != this.symInConstructor
// M1.sym == M2.sym <=> M1 == M2
}
}
// remeber, Symbol() != Symbol(), each call creates a unique one
However note that you can't ever serialize a Symbol.
If you need a serializable thingy, generate uuid or whatever
Also it may have sense to not use Symbol, but to use the class instance itself, I don't see how the Symbol may be used
Create a global constant, and use square brackets access
const MovieName = Symbol('a key for MovieName')
class Movie {
[MovieName] = "The Movie";
["myString"] = "is equivalent to:"
// myString = "is equivalent to:"
// and must be used for Symbols as
constructor() {
this[MovieName] = "The Movie in constructor"
}
// may keep is somewhere like this for usage in other places
static movieNameSymbol = MovieName
}
I'm trying to build a complex class where I want to group properties, making the instantiated object have multiple layers, instead of every property being at root level.
So far, the only way I've found to do this is by making a class with the properties to group, and then in a "parent" class add a property of the class I built.
The problem here though is that two properties not sharing the same class can't communicate with each other.
There are ways around this, but I find them all very hacky and looking bad. One would be to create a hidden element, and store data in there that a property from another class can read.
Another would be to create static properties, but then, unless you do some major work with that property, you can only have one object created from the parent class, as it'll be the same no matter the instantiation of the class.
Very basic example:
class A {
constructor(prop1){
this.property = prop1;
}
}
class B {
constructor(prop2){
this.property = prop2;
}
}
class C {
constructor(prop1, prop2){
this.PropertyA = new A(prop1);
this.PropertyB = new B(prop2);
}
}
let obj = new C(1, 1);
console.log(obj.PropertyA.property);
In this example, the property from class A can't get a value from property in class B.
So, my question is, is there another way of building the class C to keep the levels of hierarchy in the object?
I use the class structure because I like how it looks. It looks far more readable to me than the prototype structure, and I'm not building an object directly, as I would like to instantiate more of them.
It feels like I have forgotten things I've looked at to try to do this, but I'm sure it'll come to me soon enough after I post this.
Sooo...
I worked a bit on a static-solution, and basically made a private static property to hold a unique id per instantiated object, with the key-value pairs I want to be able to share between the different classes. This should only expose the methods to either set or get those values. The only requirement is that all the classes needs to be constructed with the object ID, so they can get the right value.
I understand that people will roll their eyes at my infantile tries to break the actual points of classes and such, but it works for me anyway in this specific circumstance anyway.
I'm sure there a multitude of ways to update it to ensure it runs more smoothly, but I think it works for most cases at the moment.
The code made in example code:
"use strict";
class A {
#id
#testProp
constructor(id){
this.#id = id;
this.#testProp = 10;
}
get TestProp(){ return this.#testProp + C.getSharedProp(this.#id, "BValue")};
set TestProp(newValue) { this.#testProp = newValue; C.setSharedProp(this.#id, "AValue", this.#testProp) };
}
class B {
#id
#testProp
constructor(id){
this.#id = id;
this.#testProp = 10;
}
get TestProp(){ return this.#testProp + C.getSharedProp(this.#id, "AValue")};
set TestProp(newValue) { this.#testProp = newValue; C.setSharedProp(this.#id, "BValue", this.#testProp) };
}
class C {
#id
constructor(){
this.#id = Math.random().toString(36).substr(2, 9);
this.PropertyA = new A(this.#id);
this.PropertyB = new B(this.#id);
}
static #sharedProps = {};
static getSharedProp(charId, valueName) {
if(!charId){
throw "Must supply character ID";
}
if(!valueName){
throw "Must supply name of value to return";
}
if(!(charId in this.#sharedProps)){
throw "Character ID not found";
}
if(!(valueName in this.#sharedProps[charId])){
throw valueName + "-element not found";
}
return this.#sharedProps[charId][valueName];
}
static setSharedProp(charId, valueName, value) {
if(!charId){
throw "Must supply character ID";
}
if(!valueName){
throw "Must supply name of value";
}
if(!(charId in this.#sharedProps)){
this.#sharedProps[charId] = [];
}
if(!(valueName in this.#sharedProps[charId])){
this.#sharedProps[charId][valueName] = -1;
}
if(!value){
console.warn("Value not supplied of " + valueName + ". Not updating extant value");
}else{
this.#sharedProps[charId][valueName] = value;
}
}
}
let obj = new C();
obj.PropertyA.TestProp = 20;
obj.PropertyB.TestProp = 5;
console.log(obj.PropertyA.TestProp); //should be 25; 20 from its own class and 5 from foreign class-object
console.log(obj.PropertyB.TestProp); //should be 25; 5 from its own class and 20 from foreign class-object
Can You help with this thing that I need to figure out. I started learning Js with OOP but I am kind of stuck with this, where am I making a mistake. This is the assignment I have to figure out
Create a class Car with a property that holds a number of doors and one method that prints the number of doors to the console.
class Car {
constructor(doors){
this.doors=doors
console.log(doors)
}
}
you need to create a method in the Car class to print the number of doors and then you need to instantiate the class with a given number of door & then call that method on it.
class Car {
constructor(doors){
this.doors = doors;
}
print(){
console.log(this.doors);
}
}
const bmw = new Car(4);
bmw.print()
Hey 👋
Yeah no problem :)
class Car {
constructor(doors) {
this.doors = doors;
}
printDoors() {
console.log(this.doors);
}
}
In JS OOP you have to define your member variables within the constructor by using the this keyword.
To access your variables somewhere else in the class you also have to use `this.
The printDoor() function has to be defined at its own to call it later on like this:
const numberDoors = 4;
const myCar = new Car(numberDoors);
myCar.printDoors();
// expected output: 4
I have a class (Foo) that is used to hold a list of items, the list of items of which all inherit from a base type (IBar), this list can contain any number of these items.
The issue I have is that I am trying to create a get method on Foo that takes a generic type restricted to types that inherit from IBar.
The interfaces and classes I have currently are:
interface IBar {
bar : string;
}
interface IFizz extends IBar {
buzz : string;
}
class Foo {
get<T extends IBar>() : T {
var item = this.list[0];
return item;
}
list : Array<IBar>;
}
With the code i'm trying to run being:
var foo = new Foo();
var item = foo.get<IFizz>();
I know in the above that the list is empty, but this is more trying to get the Typescript compiler not to show an error. The line that calls foo.get is fine and does not error, the problem is the get method itself.
The error i get from the above is "Type 'IBar' is not assignable to type 'T'".
If looking at C# for a reference the above would work (I believe) and would welcome any written examples to help me solve this.
Thanks
The above code would not work in C# either. Both language try to prevent you to do this, because this is not type safe. Consider the following code:
class Foo {
get<T extends IBar>() : T {
var item = this.list[0];
return item;
}
list : Array<IBar> = [ new OneClass() ];
}
var foo = new Foo();
var item = foo.get<AnotherClass>();
OneClass and AnotherClass both implement IBar, but list[0] is of type OneClass but the caller requests an instance of AnotherClass. So if the compiler would allow the code you wrote, you get item typed as AnotherClass but holding an instance of OneClass which may cause runtime errors.
Just like in C# you can force the typescript compiler to let you do this using a type assertion (or similarly a cast in C#). Although you can do this, you should have another mechanism for ensuring that the item in the array is actually of a correct type for T:
class Foo {
get<T extends IBar>() : T {
var item = this.list[0];
return item as T;
}
list : Array<IBar> = [];
}
var foo = new Foo();
var item = foo.get<IFizz>();
You're trying to assert that the item at index 0 is an IFizz, not just an IBar; that can't be assured statically given Foo's declaration, it can only be true at runtime with specific data. Although you could assert it (return item as T;), that's just hiding the problem: When code actually runs, the item at index 0 may not be an IFizz.
If the list is going to contain IFizz, it should be declared to do so. If it's going to contain any kind of IBar, it should be declared to do that, and any code using it for IFizz instances is responsible for ensuring that's really true.
Instead, Foo should be parameterized with the actual type of IBar it will contain:
class Foo<T extends IBar> {
get() : T {
var item = this.list[0];
return item;
}
list : Array<T>;
}
and then
var item = foo.get();
I'm trying scala.js and I must say that it's completely impressed! However, I try to introduce it into our production little-by-little, working side-by-side with existing JavaScript code. One thing I'm struggling with is passing complex structures from JS to Scala. For example, I have ready-made JS object that I've got from the other JS module:
h = {
"someInt": 123,
"someStr": "hello",
"someArray": [
{"name": "a book", "price": 123},
{"name": "a newspaper", "price": 456}
],
"someMap": {
"Knuth": {
"name": "The Art of Computer Programming",
"price": 789
},
"Gang of Four": {
"name": "Design Patterns: Blah-blah",
"price": 1234
}
}
}
It
has some ints, some strings (all these elements have fixed key names!), some arrays in it (which in turn has some more objects in it) and some maps (which map arbitrary string keys into more objects). Everything is optional and might be missing. Obviously, it's just a made-up example, real-life objects are much more complex, but all the basics are up here. I already have the corresponding class hierarchy in Scala which looks something like that:
case class MegaObject(
someInt: Option[Int],
someStr: Option[String],
someArray: Option[Seq[Item]],
someMap: Option[Map[String, Item]]
)
case class Item(name: Option[String], price: Option[Int])
1st attempt
My first try was to a naïve attempt to just use receiver types as is:
#JSExport
def try1(src: MegaObject): Unit = {
Console.println(src)
Console.println(src.someInt)
Console.println(src.someStr)
}
and it, obviously, fails with:
An undefined behavior was detected: [object Object] is not an instance of my.package.MainJs$MegaObject
2nd attempt
My second idea was receiving this object as js.Dictionary[String] and then doing lots of heavy typechecking & typecasting. First we'll define some helper methods to parse regular strings and integers from JS object:
def getOptStr(obj: js.Dictionary[String], key: String): Option[String] = {
if (obj.contains(key)) {
Some(obj(key))
} else {
None
}
}
def getOptInt(obj: js.Dictionary[String], key: String): Option[Int] = {
if (obj.contains(key)) {
Some(obj(key).asInstanceOf[Int])
} else {
None
}
}
Then we'll use them to parse an Item object from the same source:
def parseItem(src: js.Dictionary[String]): Item = {
val name = getOptStr(src, "name")
val price = getOptInt(src, "price")
Item(name, price)
}
And then, all together, to parse whole MegaObject:
#JSExport
def try2(src: js.Dictionary[String]): Unit = {
Console.println(src)
val someInt = getOptInt(src, "someInt")
val someStr = getOptStr(src, "someStr")
val someArray: Option[Seq[Item]] = if (src.contains("someArray")) {
Some(src("someArray").asInstanceOf[js.Array[js.Dictionary[String]]].map { item =>
parseItem(item)
})
} else {
None
}
val someMap: Option[Map[String, Item]] = if (src.contains("someMap")) {
val m = src("someMap").asInstanceOf[js.Dictionary[String]]
val r = m.keys.map { mapKey =>
val mapVal = m(mapKey).asInstanceOf[js.Dictionary[String]]
val item = parseItem(mapVal)
mapKey -> item
}.toMap
Some(r)
} else {
None
}
val result = MegaObject(someInt, someStr, someArray, someMap)
Console.println(result)
}
It, well, works, but it is really ugly. That's lots of code, lots of repetitions. It can probably refactored to extract array parsing and map parsing into something saner, but it still feels bad :(
3rd attempt
Tried the #ScalaJSDefined annotation to create something along the lines of "facade" class, as described in documentation:
#ScalaJSDefined
class JSMegaObject(
val someInt: js.Object,
val someStr: js.Object,
val someArray: js.Object,
val someMap: js.Object
) extends js.Object
Just printing it out kind of works:
#JSExport
def try3(src: JSMegaObject): Unit = {
Console.println(src)
Console.println(src.someInt)
Console.println(src.someStr)
Console.println(src.someArray)
Console.println(src.someMap)
}
However, as soon as I'm trying to add a method to JSMegaObject "facade" that will convert it to its proper Scala counterpart (even a fake one like this):
#ScalaJSDefined
class JSMegaObject(
val someInt: js.Object,
val someStr: js.Object,
val someArray: js.Object,
val someMap: js.Object
) extends js.Object {
def toScala: MegaObject = {
MegaObject(None, None, None, None)
}
}
trying to call it fails with:
An undefined behavior was detected: undefined is not an instance of my.package.MainJs$MegaObject
... which kind of really reminds me of attempt #1.
Obviously, one can still do all the typecasting in the main method:
#JSExport
def try3real(src: JSMegaObject): Unit = {
val someInt = if (src.someInt == js.undefined) {
None
} else {
Some(src.someInt.asInstanceOf[Int])
}
val someStr = if (src.someStr == js.undefined) {
None
} else {
Some(src.someStr.asInstanceOf[String])
}
// Think of some way to access maps and arrays here
val r = MegaObject(someInt, someStr, None, None)
Console.println(r)
}
However, it quickly becomes just as ugly as attempt #2.
Conclusion so far
So, I'm kind of frustrated. Attempts #2 and #3 do work, but it really feels that I'm missing something and it shouldn't be that ugly, uncomfortable, and require to write tons of JS-to-Scala types converter code just to access the fields of an incoming JS object. What is the better way to do it?
Your attempt #4 is close, but not quite there. What you want is not a Scala.js-defined JS class. You want an actual facade trait. Then you can "pimp" its conversion to your Scala class in its companion object. You must also be careful to always use js.UndefOr for optional fields.
#ScalaJSDefined
trait JSMegaObject extends js.Object {
val someInt: js.UndefOr[Int]
val someStr: js.UndefOr[String],
val someArray: js.UndefOr[js.Array[JSItem]],
val someMap: js.UndefOr[js.Dictionary[JSItem]]
}
object JSMegaObject {
implicit class JSMegaObjectOps(val self: JSMegaObject) extends AnyVal {
def toMegaObject: MegaObject = {
MegaObject(
self.someInt.toOption,
self.someStr.toOption,
self.someArray.toOption.map(_.map(_.toItem)),
self.someMap.toOption.map(_.mapValues(_.toItem)))
}
}
}
#ScalaJSDefined
trait JSItem extends js.Object {
val name: js.UndefOr[String]
val price: js.UndefOr[Int]
}
object JSItem {
implicit class JSItemOps(val self: JSItem) extends AnyVal {
def toItem: Item = {
Item(
self.name.toOption,
self.price.toOption)
}
}
}
Getting these objects from JavaScript to Scala is actually fairly easy. You were on the right track, but needed a little bit more -- the trick is that, for cases like this, you need to use js.UndefOr[T] instead of Option[T], and define it as a facade. UndefOr is a Scala.js type that means exactly "this is either a T or undefined", and is mainly intended for interaction cases like this. It includes a .toOption method, so it's easy to interface with Scala code. You can then simply cast the object you get from JavaScript to this facade type, and everything ought to work.
Creating one of these JSMegaObjects from Scala takes a bit more work. For cases like this, where you are trying to create a complex structure with lots of fields that might or might not exist, we have JSOptionBuilder. It's named like that because it was written for the big "options" objects that are common in jQuery, but it's not jQuery-specific. You can find it in the jsext library, and documentation can be found on the front page there.
You can also see a moderately complex fully-worked example in the JQueryAjaxSettings class in jquery-facade. That shows both the JQueryAjaxSettings trait (the facade for the JavaScript object) and the JQueryAjaxSettingsBuilder (which lets you construct one from scratch in Scala).