Kotlin Companion Objection unresolved references - android

I have a Kotlin class with companion object which sees some fields of the parent class and does not see others. There is no option in Android Studio to import.
class A{
var a = 1
var b = 2
companion object {
a += 1// visible and imported
b += 1// unresolved reference
}
}
I do not want to create this variable inside the companion object.

You are absolutely incorrect.
You cannot access members of class inside companion object at all. But you can use companion`s members in your class.
If you see kotlin bytecode you will see that Companion object compiles to
public static final class Companion {
private Companion() {
}
// $FF: synthetic method
public Companion(DefaultConstructorMarker $constructor_marker) {
this();
}
}
Since Companion is static class it can exist without class where it is declared.
So in your case you can not access a and b because probably they are not exists.
They are not accessable for you too, but probably you cought IDE bug and it doesnt give you error

You cannot access instance variables from static context (companion), this is the same as Java code

Android Studio imported A class variables. In imports i see import package.A.a, but not import package.A.b
import package.A.a simply doesn't make sense for a class property a, and companion object wouldn't require an import from the class it's companion to anyway. My best guess is that it's importing from an object in a different package.

Related

Android + Kotlin + Hilt: Injecting into static methods classes

I'm not very clear about the best way to inject into a static methods helper class (lets say a Custom class).
I'm kinda new to Kotlin, and as I've learnt we can access a method statically in two ways:
Object class.
Class + companion object.
To start, I'm not sure which one is the most recommended one (if there is a best practice regarding this), but my "problem" arises when needing to inject dependencies into a static method class.
Let's go with a simple example:
I have a static methods class called AWUtils (not decided if it should be an object class or a class with companion object yet though, and this will most likely depend on the injection mechanism recommended) with the next method:
fun setAmpersand2Yellow(text2Replace: String, target: String): String {
return text2Replace.replace(
target, "<span style=\"color:" +
app.drawerFooterColor + ";\">" + target + "</span>"
)
}
Here, app is the instance of my AppSettings class which holds all app configuration so, as you see setAmpersand2Yellow needs AppSettings, and of course I would't pass it as a parameter by any means, so it's a AWUtils dependence.
Using AWUtils as a class with companion object for the static methods I cannot inject directly AppSettings into company object as far as I know (at least I cannot do constructor injection, let me know if I'm wrong) and if I inject into companion object parent class (AWUtils) constructor then I don't know how to access those dependences from the companion object itself (the child).
If I use fields injection in AWUtils as a class then it complains than lateinit field has not been initialised and I don't know how to deal with this, because as far as I know lateinit fields are initialised in onCreate, which does not exist in this kind of classes.
One other possibility is to use an object with fields and set the dependencies values from caller in a static way before calling the method, for example:
object AWUtils {
var app: AppSettings? = null
fun setAmpersand2Yellow(text2Replace: String, target: String): String {
return text2Replace.replace(
target, "<span style=\"color:" +
app.drawerFooterColor + ";\">" + target + "</span>"
)
}
}
#AndroidEntryPoint
class OtherClass
#Inject constructor(private val app: AppSettings) {
fun AnyFunction() {
var mystr = "whatever"
AWUtils.app = app
var yellowStr = AWUtils.setAmpersand2Yellow(myStr)
}
}
In the end, I'm not sure on how to supply dependencies to a static methods class and which form of "static" class should I choose.
Edit 1:
Apart from my ApSettings class, I need a context, like for example in this next isTablet method:
val isTablet: String
get() {
return ((context.resources.configuration.screenLayout
and Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE)
}
In the end, I need a context and my AppSettings (or any other custom classes) to be injected anyway in a class with static methods.
Edit 2:
I could do (from the activity):
AWUtils.context = this
AWUtils.app = app
var isTablet = AWUtils.isTablet
And it works, but rather to be in the need of assigning a value to two fields (or more) every time I need to call a static method, I would prefer the fields to be injected in any way.
That's what dependency injection is meant for, isn't it?
Edit 3: I'm starting to be fed up with Hilt, what is supposed would have been created to simplify our life, only makes our programming life much more complicated.
As you clarified in the comments, you want to have your utils class accessible in an easy way across your codebase, so this answer will focus on that and on your original questions.
I'm kinda new to Kotlin, and as I've learnt we can access a method statically in two ways: Object class or Class + companion object.
Kotlin does not have Java-style statics. One reasoning behind it was to encourage more maintainable coding practices. Static methods and static classes are also a nightmare for testing your code.
In Kotlin you would go with an object (but a class + companion object would work in the same way)
object AWUtils {
lateinit var appContext: Context
lateinit var appSettings: AppSettings
fun initialize(
appContext: Context,
appSettings: AppSettings,
// more dependencies go here
) {
this.appContext = appContext
this.appSettings = appSettings
// and initialize them here
}
val isTablet: Boolean
get() = ((appContext.resources.configuration.screenLayout
and Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE)
fun setAmpersand2Yellow(text2Replace: String, target: String): String {
return text2Replace.replace(
target, "<span style=\"color:" +
appSettings.drawerFooterColor + ";\">" + target + "</span>"
)
}
}
Since this object should be accessible across the whole application it should be initialized as soon as possible, so in Application.onCreate
#HiltAndroidApp
class Application : android.app.Application() {
// you can inject other application-wide dependencies here
// #Inject
// lateinit var someOtherDependency: SomeOtherDependency
override fun onCreate() {
super.onCreate()
// initialize the utils singleton object with dependencies
AWUtils.initialize(applicationContext, AppSettings())
}
Now anywhere in your app code you can use AWUtils and AppSettings
class OtherClass { // no need to inject AppSettings anymore
fun anyFunction() {
val mystr = "whatever"
val yellowStr = AWUtils.setAmpersand2Yellow(myStr)
// This also works
if (AWUtils.isTablet) {
// and this as well
val color = AWUtils.appSettings.drawerFooterColor
}
}
}
There is another way in Kotlin to write helper/util functions, called extension functions.
Your isTablet check might be written as an extension function like this
// This isTablet() can be called on any Configuration instance
// The this. part can also be omitted
fun Configuration.isTablet() = ((this.screenLayout
and Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE)
// This isTablet() can be called on any Resources instance
fun Resources.isTablet() = configuration.isTablet()
// This isTablet() can be called on any Context instance
fun Context.isTablet() = resources.isTablet()
With the above extension functions in place the implementation inside AWUtils would be simplified to
val isTablet: Boolean
get() = appContext.isTablet()
Inside (or on a reference of) any class that implements Context, such as Application, Activity, Service etc., you can then simply call isTablet()
class SomeActivity : Activity() {
fun someFunction() {
if (isTablet()) {
// ...
}
}
}
And elsewhere where Context or Resources are available in some way, you can simply call resources.isTablet()
class SomeFragment : Fragment() {
fun someFunction() {
if (resources.isTablet()) {
// ...
}
}
}
Edit 3: I'm starting to be fed up with Hilt, what is supposed would have been created to simplify our life, only makes our programming life much more complicated.
Yeah, Hilt is focusing on constructor injection and can only do field injection out-of-the-box in very limited cases, afaik only inside Android classes annotated with #AndroidEntryPoint and inside the class extending the Application class when annotated with #HiltAndroidApp.
Docs for #AndroidEntryPoint say
Marks an Android component class to be setup for injection with the standard Hilt Dagger Android components. Currently, this supports activities, fragments, views, services, and broadcast receivers.
If you feel that you need a lot of field injection, because you are working with "static"-like objects in Kotlin, consider using Koin instead of Hilt for your next project.

Kotlin - Assigning a static class reference to a variable

"R, BuildConfig, DataBinding and BR" classes in Android are created according to the package name declared in AndroidManifest.xml.
When using them in a class, this package name is imported according to its path. We don't want this because it complicates PRs.
For this, I created a class like the one below.
object App {
val BuildConfig: BuildConfig get() = BuildConfig()
val R: R get() = R()
val BR: BR get() = BR()
}
But for example, when I try to access App.R.layout, your "layout" section gets red. So I can't access those statements this way.
For example, classes are automatically created in the following types.
public final class BuildConfig {}
public final class R extends Object {}
public final class BR extends Object {}
I guess I need to assign a static class reference to a variable.
Do you have a solution suggestion?

Junit 4 test inner class in kotlin

I use Junit4 and kotlin.
I use the Enclosed for the inner class test.
import org.junit.Test
import org.junit.experimental.runners.Enclosed
import org.junit.runner.RunWith
#RunWith(Enclosed::class)
class SampleTest {
var text = "parent class"
class Class1 {
#Test
fun `print the text`() {
println(text)
}
}
inner class Class2 {
#Test
fun `print the text`() {
println(text)
}
}
}
in Class1 and Class2, need the text variable.
I use the inner for an access child class to parent class.
but I have a problem, the test function is removed and I can't test that. see the photo.
can I test the inner class in kotlin with Junit4?
Class1 is a plain nested class that happens to be in SampleTest. It's just an organisational thing, your Class1 instance doesn't have any reference to a SampleTest instance, so it can't access text (not without being passed an instance explicitly).
If you want a nested class to be able to access an enclosing instance like that, you need to mark it as inner, like with Class2. That way you can create an instance of Class2 through an instance of SampleClass, like
val sample = SampleClass()
val class2 = sample.Class2()
sample.text = "wow!"
class2.`print the text`()
You can read about this stuff in the docs if it's unfamiliar
So yeah, if JUnit constructs a Class1 instance, it doesn't know what text is, since that's an instance variable in some other unrelated class.
And I'm assuming it doesn't know how to create Class2, since it requires a SampleTest instance to do that. All the examples for Enclosed use static nested classes, and like the Java docs say:
A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
so that's basically the same as Kotlin's (non-inner) nested classes, like your Class1. You probably can't use inner classes (not to organise and automatically run tests, anyway)
You probably want to stick text in a companion object if you're organising your tests in classes (or just a top-level object outside of SampleClass, or just in the top level of the file if you really want - just somewhere it can be accessed by any other class in a "static" way
we can use 3 wayes
use NestedRunner this
use HierarchicalContextRunner this
use Enclosed and the companion object and don't use the inner class
#RunWith(Enclosed::class)
class TEST {
companion object {
var text = "parent class"
}
class Class1 {
#Test
fun `print the text`() {
println(text)
}
}
class Class2 {
#Test
fun `print the text`() {
println(text)
}
}
}

Kotlin - Inheritance in Object expression

I need to inherit the Object A from Object B, were both the objects consist of constants only.
Example
Object A {
const val a1 = "some_data_1"
const val a2 = "some_data_2"
}
Object B : A {
const val b1 = "some_data_3"
}
is it feasible to achieve this in kotlin ?
Kotlin is an object-oriented programming (OOP) language. We can inherit object A from object B for that we have to to allow class "A" to be inherited, for that we need to attach the open modifier before the class to make it non-final.
For the const we have to use companion object, which is an object that is common to all instances of that class.
open class A {
companion object {
const val a1 = "some_data_1"
const val a2 = "some_data_2"
}
}
class B : A() {
companion object {
const val b1 = "some_data_3"
}
val a_1 = a1
val a_2 = a2
}
Check this link to understand inheritance
Check this link to understand Companion Object
open class A {
companion object {
const val a1 = "some_data_1"
const val a2 = "some_data_2"
}
}
class B : A() {
companion object {
const val b1 = "some_data_3"
}
val a_1 = a1
val a_2 = a2
}
for a class to be inherited in Kotlin it should be open for example open class A {}
for class B to extends class A should add the class B : A()
for constants should be inside a companion object {}
I would probably dive a bit deeper.
Object in your example is an Object Declaration.
You should have a look at this doc describing Object Declarations and Object Expressions.
The question is - Why would you need to have one class only with constants extend another(also containing only const vals)?
Object Declarations are Kotlin built in Singletons and BTW are thread safe.
Example :
object DeviceProvider {
private val _devices = ArrayList<Device>()
fun getDevices() = _devices as List<Device>
fun registerDevice(device: Device) {
_devices.find { it == device } ?: _devices.add(device)
}
}
Usage :
fun addDevice(){
ServiceProvider.registerDevice(Device("1234"))
}
Object declarations are allowed to extend open classes and interfaces - so you can define a behavior or even a state via inheritance. As usual you can have a look at Kotlin docs about inheritance, those are exhaustive and nice read.
Still if we are talking about common approaches defining const values - then separate file is the best solution, if of course that value should be bound to any specific class. Here is a nice point of view(thanks Marko for your answer) :
In Java you're forced to put all static field and method declarations
in a class and often you even have to create a class just for that
purpose. Coming to Kotlin, many users look for the equivalent facility
out of habit and end up overusing companion objects.
Kotlin completely decouples the notions of a file and a class. You can
declare any number of public classes is the same file. You can also
declare private top-level functions and variables and they'll be
accessible only to the classes within the same file. This is a great
way to organize closely associated code and data.

How to access a member of a class "statically" in kotlin?

In Java and Android, we can do this:
public static MyApplication extends Application {
private static Context appContext;
public void onCreate() {
appContext = this;
}
public static Context getAppContext() {
return appContext;
}
}
so that, somewhere else, we can do this:
appContext = MyApplication.getAppContext();
How do we do this in Kotlin? I've been going round in circles for the past hour or so.
Thanks in advance.
//Edit
Perhaps I should have been clearer. I meant how can we write the above in Kotlin and use it in Kotlin.
In Kotlin this is called the 'companion object':
class MyApplication: Application {
companion object {
var appContext: Context? = null
private set
}
}
The key element I was missing was the use of an init block to set the appContext that is inside the companion object (I had already tried the companion object path but was struggling to actually get appContext set).
See code below:
class MyApplication : Application() {
init {
appContext = this
}
companion object {
lateinit var appContext: Context
private set
}
}
This is then callable as usual via:
val testContext = MyApplication.appContext
Assumed you have some java code in android and you want to convert it to kotlin code:
Visit Link
find Convert from java
it's help me to convert java code I've found on internet and converting it to kotlin code,
may this answer not help you about your question, but it would help you to convert what you know in java that you don't know how-to-do in kotlin
you can use it this way
companion object{
//your static fields
}
to call it from kotlin ==> ClassName.FieldName
to call it from java ==> ClassName.Companion.getFieldName()
It seems like you want only one object of this class at runtime. This is called a singleton. There are recommendations to implement that properly in Java. Luckily Kotlin directly allows you to declare singleton objects on the top scope:
val o = object { your attributes and methods here}

Categories

Resources