there is this class hierarchy:
class A {
constructor (obj) {
this.obj = obj
}
}
class B extends A {
static createObj () {
return {from: 'B'};
}
constructor () {
const obj = B.createObj();
super(obj);
}
}
I would like to extend this such that:
class C extends B {
static createObj () {
return { from: 'C' };
}
}
//such that:
console.log(new C().obj.from) // 'C'
BUT therefore I need to change const obj = B.createObj() to something like: const obj = Object.getPrototypeOf(this).constructor.createObj();, what is throwing this error:
ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
So basically I would like to override a method that creates an object to be used within the super() call. Since this cannot be used before that, I chose to use a static method. Is there any way to reference the static method, without using this and without overriding the constructor as well?
If you really want your this.obj=obj to be done only in class A for some reason, then I would do:
class A {
constructor(obj) {
this.obj = obj
}
}
class B extends A {
static createObj() {
return { from: 'B' };
}
constructor(obj) {
if (!obj) obj = B.createObj();
super(obj);
}
}
class C extends B {
static createObj() {
return { from: 'C' };
}
constructor(obj) {
if (!obj) obj = C.createObj();
super(obj);
}
}
console.log(new C().obj.from)
Output:
"C"
But in my opinion the best OOP approach would be this:
class A {
constructor(obj) {
this.obj = obj
}
}
class B extends A {
static createObj() {
return { from: 'B' };
}
constructor(obj) {
super(obj);
this.obj = B.createObj();
}
}
class C extends B {
static createObj() {
return { from: 'C' };
}
constructor(obj) {
super(obj);
this.obj = C.createObj();
}
}
console.log(new C().obj.from)
Output:
"C"
The 2nd approach allows to satisfy the pattern "call super before doing anything else" that can prevent bugs.
It's up to you to chose which one better suits your needs, but both prints "C" without requiring Object.getPrototypeOf(this).constructor.createObj()
Related
When I have two classes (A and B) and A has a function called myFunA which then calls myFunB (inside of class B), is it possible for code in myFunB to obtain a reference to the class A that is used to call myFunB? I can always pass the reference as a parameter but I am wondering if Kotlin has a way of allowing a function to determine the instance of the parent caller.
class A {
fun myFunA() {
val b = B()
b.myFunB() {
}
}
}
class B {
fun myFunB() {
// Is it possible to obtain a reference to the instance of class A that is calling
// this function?
}
}
You can do it like this:
interface BCaller {
fun B.myFunB() = myFunB(this#BCaller)
}
class A : BCaller {
fun myFunA() {
val b = B()
b.myFunB()
}
}
class B {
fun myFunB(bCaller: BCaller) {
// you can use `bCaller` here
}
}
If you need a reflection-based approach, read this.
I have this enum in swift
#objc(PaymentMethods)
public enum PaymentMethods: Int, RawRepresentable {
public typealias RawValue = String
case card
case account
case paypal
public var rawValue: RawValue {
switch self {
case .card:
return "CARD"
case .account:
return "ACCOUNT"
case .paypal:
return "PAYPAL"
}
}
public init(rawValue: RawValue){
switch rawValue {
case "CARD":
self = .card
case "ACCOUNT":
self = .account
case "PAYPAL":
self = .paypal
default:
self = .card
}
}
}
And this property in a class.
#objc public class SomeClass: ExtendingSomeOtherStuffs {
var supportedPaymentMethods:[PaymentMethods]!
}
my problem is how to bridge supportedPaymentMethods into Objective-C and use it.
I have looked at this post and this but still can't figure it out.
can someone help me out with an example at least.
Am trying to use this in Native-script and I need to expose that property from Swift to Objective
You can do it like so:
#objc public class SomeClass: NSObject {
var supportedPaymentMethods: [PaymentMethods]
#objc init(supportedPaymentMethods: [String]) {
self.supportedPaymentMethods = supportedPaymentMethods.map { .init(rawValue: $0) }
}
}
and use it like this in your Objective-C code:
[[SomeClass alloc] initWithSupportedPaymentMethods:#[#"ACCOUNT", #"CARD", #"PAYPAL"]];
If you don't want your class initializer to take any String I would suggest doing the following:
Make your init(rawValue:) failable and return nil when the argument is invalid:
public init?(rawValue: RawValue) {
switch rawValue {
case "CARD":
self = .card
case "ACCOUNT":
self = .account
case "PAYPAL":
self = .paypal
default:
return nil
}
}
Use compactMap instead of map in the init of the SomeClass like so:
#objc init(supportedPaymentMethods: [String]) {
self.supportedPaymentMethods = supportedPaymentMethods.compactMap { .init(rawValue: $0) }
}
(it will eliminate the nil values)
i want declare a function that returns a common type or its extended type
interface Common {
id: number;
}
interface AdditionalInformation extends Common {
myname: string;
}
Surely the function returns an object containing the id property
and wishing it could also return the myname property
I tried to declare the function like this:
export class Lib {
public static lowestCommonDenominator <T extends Common>(): Common {
const a: Common = { id: 1 };
return a;
}
public static firstCaseFunction(): Common {
const ok: Common = this.lowestCommonDenominator();
return ok;
}
public static secondCaseFunction(): AdditionalInformation {
// Property 'myname' is missing in type 'Common' but required in type 'AdditionalInformation'.ts(2741)
const ko: AdditionalInformation = this.lowestCommonDenominator();
return ko;
}
}
But when I assign the function to an extended type, I get the error:
Property 'myname' is missing in type 'Common' but required in type
'AdditionalInformation'.ts(2741)
Is it possible to implement what I want?
This code snippet removes the error
export class Lib {
public static lowestCommonDenominator <T extends Common>(): T {
const a: Common = { id: 1 };
return a as T;
}
public static firstCaseFunction(): Common {
const ok: Common = this.lowestCommonDenominator();
return ok;
}
public static secondCaseFunction(): AdditionalInformation {
const ko: AdditionalInformation = this.lowestCommonDenominator<AdditionalInformation>();
return ko;
}
}
Assuming the I have a function to be test below, declare at the file named "Utils.kt"
//Utils.kt
fun doSomething() = 1
Then we create a test class to test it
//UtilsTest.kt
#RunWith(JMockit::class)
class UtilsTest {
#Test
fun testDoSomething() {
object : Expectation() {
init {
doSomething()
result = 2
}
}
assertEquals(2, doSomething())
}
}
I want to mock doSomething, make it return 2, but it won't work, actual result is 1
Is there any workaround for this purpose?
A workaround mock it in Java side as you cannot reference the UtilsKt class from Kotlin files.
#RunWith(JMockit.class)
public final class UtilsFromJavaTest {
#Test
public final void testDoSomething(#Mocked #NotNull final UtilsKt mock) {
new Expectations() {
{
UtilsKt.doSomething();
this.result = 2;
}
};
Assert.assertEquals(2, UtilsKt.doSomething());
}
}
Thanks to #aristotll, we can simply extends the workaround to make it more easier to use.
first, declare a java class that return the UtilsKt class
//TopLevelFunctionClass.java
public class TopLevelFunctionClass {
public static Class<UtilsKt> getUtilsClass() {
return UtilsKt.class
}
}
then, mock this class in expectation using partial mock
//UtilsTest.kt
#RunWith(JMockit::class)
class UtilsTest {
#Test
fun testDoSomething() {
object : Expectation(TopLevelFunctionClass.getUtilsClass()) {
init {
doSomething()
result = 2
}
}
assertEquals(2, doSomething())
}
}
Since TypeScript 1.6, we can easily create inner classes with class expressions. In other OOP-centric languages like Java, inner classes can access members of the outer class, even private ones.
This behavior is similar to concept of closures, where function could access variables from the scope in which it was defined.
Why I can't achieve this in TypeScript? Does specification of classes in ECMAScript 2015 plays role here?
Code that presents expected behavior:
class OuterClass {
private outerField = 1337;
public InnerClass = class {
public accessOuter() {
return this.outerField; // outerField not defined
}
}
}
var outer = new OuterClass();
var inner = new outer.InnerClass();
var win = inner.accessOuter();
It's easier to understand why you can't do that if you look at the compiled javascript of your code:
var OuterClass = (function () {
function OuterClass() {
this.outerField = 1337;
this.InnerClass = (function () {
function class_1() {
}
class_1.prototype.accessOuter = function () {
return this.outerField; // outerField not defined
};
return class_1;
}());
}
return OuterClass;
}());
As you can see, outerField is defined as a member of OuterClass like so:
this.outerField = 1337;
When you try to access it in your InnerClass you do:
return this.outerField;
But the this here is the instance of class_1 and not OuterClass so there's no outerField in this.
Also, you have no access from the inner class to the instance of the outer class.
The way this is solved in java is like so:
class OuterClass {
private int outerField = 1337;
public class InnerClass {
public int accessOuter() {
return OuterClass.this.outerField;
}
}
}
But there's no equivalent to OuterClass.this.outerField in typescript/javascript.
Look at typescript inner classes more like static inner classes in java, but here too you'll only be able to access public properties:
class OuterClass {
public static outerField = 1337; // has to be public
public InnerClass = class {
public accessOuter() {
return OuterClass.outerField;
}
}
}
You can pass an instance of the outer class to the inner class:
class OuterClass {
public outerField = 1337;
public InnerClass = class {
constructor(private parent: OuterClass) {}
public accessOuter() {
return this.parent.outerField;
}
}
}
But again, you'll need to have outerField public.
Edit
In case you want to achieve something that will simulate the needed behavior (that is, the inner class instance will have access to a private outer class members), then you can do something like this:
interface OuterClassProxy {
outerField: number;
}
interface IInnerClass {}
class OuterClass {
private outerField = 1337;
static InnerClass = class implements IInnerClass {
constructor(private parent: OuterClassProxy) {}
public accessOuter() {
return this.parent.outerField;
}
}
public createInnerClass(): IInnerClass {
let outerClassInstance = this;
return new OuterClass.InnerClass({
get outerField(): number {
return outerClassInstance.outerField;
},
set outerField(value: number) {
outerClassInstance.outerField = value;
}
});
}
}
It's quite a lot of work, but it will do it.
#Nitzan 's answer is great. I just wanted to add that I came up with this recently, maybe it helps:
class Outer {
constructor() {
this.val = 1337;
}
get Inner() {
let Outer = this;
return class {
accessVal() { return Outer.val; }
}
}
}
new (new Outer()).Inner().accessVal(); // 1337
Here is the correct way to do this in Typescript:
class OuterClass {
private outerField = 1337;
get InnerClass() {
const thatOuterField = this.outerField // <-- Notice this addition
return class {
public accessOuter() {
return thatOuterField; // outerField not defined
}
}
}
}
let outer = new OuterClass();
let inner = new outer.InnerClass();
let win = inner.accessOuter();
alert(win); // test works!
No need for anything convoluted.
This one did not work so bad for me:
function use<T>(value: T) {return new class {with<U>(f: (value: T) => U) {return f(value)}}}
class OuterClass {
private outerField = 1337;
InnerClass = use(this).with(outerThis => class {
accessOuter() {
return outerThis.outerField; // outerField not defined
}
}
}
const outer = new OuterClass()
const inner = new outer.InnerClass()
const win = inner.accessOuter()
console.log(win)