How to know if object is a singleton in Kotlin? - object

I would like to define toString()in superclass so, that it detects that class instance is a singleton (an object) and print its name.
Is it possible in Kotlin?

The following objectInstance property of KClass can be helpful:
/**
* The instance of the object declaration, or `null` if this class is not an object declaration.
*/
public val objectInstance: T?
Here's an example:
object Singleton
println(Singleton::class.objectInstance) // xx.Singleton#77a57272
println(""::class.objectInstance) //null

Related

How to acces shared viewModel in my recyclerAdapter

My viewModel contains some variables such as how many cardViews should be created in the recyclerView. Therefore, I am looking for a way to access the same viewModel object in my adapter class. Is there a way to do so or a better alternative? My code is in kotlin
class RecyclerAdapter : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
private val gameViewModel: GameViewModel by activityViewModels()
Since you have provided only 2 lines of code it is hard to know exactly what you are doing wrong.
Normally you would retrieve a ViewModel in an Activity class or a Fragment class like this
class MyActivity /* other stuff */ {
// this line produces/retrieves an instance of GameViewModel
// where its owner is MyActivity
private val gameViewModel: GameViewModel by viewModels()
}
Then somewhere else inside your activity class, you instantiate your RecycleAdapter class. There you would pass the gameViewModel to it. Of course, to be able to do that your RecyclerAdapter would either have to accept a GameViewModel as a constructor parameter, or through a setter, or some other function call.
Here is an example through a constructor parameter. Your RecyclerAdapter class would have to be defined something like this (note that this is Kotlin concise syntax for declaring properties and initializing them from the primary constructor)
class RecyclerAdapter(
private val gameViewModel: GameViewModel,
// add more constructor parameters/class properties here if needed
) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
// other class properties that you don't want to initialize
// through the primary constructor
// ...
// the class body where you implement RecyclerView.Adapter<> methods
// ...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// gameViewModel can be used here
gameViewModel.doSomething()
}
}
And as a last step, modify the line in your code, where you create your RecyclerAdapter instance
// here we create a new RecyclerAdapter and pass the gameViewModel to it
val adapter = RecyclerAdapter(gameViewModel)
recyclerView.adapter = adapter
Your Fragment's views should have a shorter lifecycle than your associated ViewModel, so it should be OK to pass it in as a constructor parameter.
class RecyclerAdapter(private val gameViewModel: GameViewModel) :
RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {
//...
}
Then pass the view model reference in from the Fragment when you instantiate the adapter in onViewCreated().
Personally, I wouldn't do this because presumably your ViewModel has lots of stuff in it that is irrelevant to the Adapter. Separation of concerns. I would make parameters only for the properties that are needed and let the Fragment pass them along from the ViewModel.

What is the difference between the 'instanceof' and 'in' keywords?

For the purposes of verifying class membership, the in and instanceof keywords appear to behave identically. So what's the difference between the two? Is there even a difference at all? There are several questions on StackOverflow (here or here) where both keywords are given as solutions for this purpose, but there is no mention on the difference between the two or when it is more appropriate to use one over the other. Additionally, the official documention mentions that the in keyword is equivalent to calling an object's isCase() method, but doesn't detail what the instanceof keyword does.
Both keywords appear to behave identically with respect to class inheritance and interface implementation:
class MyMap extends LinkedHashMap { }
def foo = new LinkedHashMap()
def bar = new MyMap()
println("LinkedHashMap instance is 'in' LinkedHashMap: ${foo in LinkedHashMap}")
println("LinkedHashMap instance is 'instanceof' LinkedHashMap: ${foo instanceof LinkedHashMap}")
println("LinkedHashMap instance is 'in' Map: ${foo in Map}")
println("LinkedHashMap instance is 'instanceof' Map: ${foo instanceof Map}")
println("MyMap instance is 'in' LinkedHashMap: ${bar in LinkedHashMap}")
println("MyMap instance is 'instanceof' LinkedHashMap: ${bar instanceof LinkedHashMap}")
println("MyMap instance is 'in' Map: ${bar in Map}")
println("MyMap instance is 'instanceof' Map: ${bar instanceof Map}")
Output:
LinkedHashMap instance is 'in' LinkedHashMap: true
LinkedHashMap instance is 'instanceof' LinkedHashMap: true
LinkedHashMap instance is 'in' Map: true
LinkedHashMap instance is 'instanceof' Map: true
MyMap instance is 'in' LinkedHashMap: true
MyMap instance is 'instanceof' LinkedHashMap: true
MyMap instance is 'in' Map: true
MyMap instance is 'instanceof' Map: true
The main difference is that instanceof is a Java keyword, while obj in SomeClass is an equivalent of SomeClass.isCase(obj) method call as you mentioned in your question.
There is one major implication: instanceof cannot be overridden and as Oracle docs says:
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
Class.isCase(obj) is implemented as follows:
/**
* Special 'Case' implementation for Class, which allows testing
* for a certain class in a switch statement.
* For example:
* <pre>switch( obj ) {
* case List :
* // obj is a list
* break;
* case Set :
* // etc
* }</pre>
*
* #param caseValue the case value
* #param switchValue the switch value
* #return true if the switchValue is deemed to be assignable from the given class
* #since 1.0
*/
public static boolean isCase(Class caseValue, Object switchValue) {
if (switchValue instanceof Class) {
Class val = (Class) switchValue;
return caseValue.isAssignableFrom(val);
}
return caseValue.isInstance(switchValue);
}
Source: org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L1121
As you can see based on the source code Groovy's obj in SomeClass is not an alias to instanceof, because it does a bit more. However, there is one important thing worth mentioning - you can override isCase() implementation, but you can't change how instanceof Java keyword behaves. Overriding Class.isCase() may cause some damage to your code if you use it as an alternative to Java's instanceof keyword.

Is it possible in .net to declare variable by class string name, but no direct class name?

I want a magic to happen like that...
class SomeClass {}
public static void main()
MagicFunctionOrMacrosOrSomethingThatGetTypeOf("SomeClass") some_var = null;<br />
}
Maybe it's crazy, but is it possible?
I need it to avoid crazy large switch case, because has a lot of classes, but at certain point of code is unable to tell what of the classes to create.
Let's have an example:
I have base class:
class baseCLASS {}
have a lot of child classes:
class class1 : baseCLASS {}
class class2 : baseCLASS {}
...
class classn : baseCLASS {}
have some flag that comes from outside to events handler:
string class_name; //actually i use int flag that should have connected with string names in dictionary.
have forced to make this:
switch(class_name)
case "class1":
class1 some_class = new class1();
some_class.RunHandler();
break;
case "class2":
class2 some_class = new class2();
some_class.RunHandler();
break;
case "classn":
classn some_class = new classn();
some_class.RunHandler();
break;
}
I want to replace that large switch statement by something like this:
MagicFunctionOrMacrosOrSomethingThatGetTypeOf(class_name) some_var = null;
... some initialization actions with some_var
some_var.Build();
some_var.RunHandler();
oh my...
You have two problems:
Given user input, you want to instantiate an object of a varying class. For this, you want a mapping between user input and .NET type name. For the first: you can use a convention -- ensure that the type name matches the input; or you can use a Dictionary<string,type>, and populate it; or you can attach an attribute to each class, showing which "verb" it handles. Once you've done that, you can use Activator.CreateInstance to (at runtime) create an instance of your unknown class. This returns object.
Calling methods on the unknown object. Either define a base class or common interface for the classes (e.g. IRunnable or something), or use dynamic, which gives you duck typing.

Constructor and object intitiation

When we access "this \ Me" in the constructor of any class, how is it that "this" is already available while its yet getting constructed? Has a temporary creation of the instance already happened before the constructor call? If so then does this mean these Constructors are called after the actual object initialisation?
the object is created and the memory is allocated before you initialize it with the constructor....
ex
1. you create the object;
MyObject myObject;
2. you initialize it
myObject = new MyObject();
these 2 steps are also done when you are doing this:
MyObject myObject = new MyObject();
Edit:
in the constructor this goes for myObject
In C++, when you have
Foo::Foo(int x)
: frob(x) {
this->frob = x;
}
then the construction really happens exactly between then : and the first brace:
:<here>{
In the the body of that constructor, the object is fully constructed, therefore, using this there is well defined.

CDialog Object assigning

CDialog *m_Dlg = NULL;
m_Dlg = this;
What happens if we assign a CDialog object to this, like in the above example?
It means that m_Dlg now points to the class instance which function is currently being executed. It also means that the function is a member of class of type CDialog or derived from it.

Resources