My SDK exposes a Java interface that has only static methods, e.g.
public interface MyDevice {
public static void setLocation(Location location) {…}
public static Location getLocation() {…}
}
In Java app that uses the SDK, my customers can use these as if it were a singleton, e.g.
Location currentLocation = MyDevice.getLocation();
When this SDK is integrated into a Kotlin app, it would be natural to express the same as a property:
val currentLocation = MyDevice.location
The problem is, this built-in interop works for non-static methods only.
I can create a singleton in Kotlin and have it handle the translation:
object myDevice {
var location: Location
get() = MyDevice.getLocation()
set(location) = MyDevice.setLocation(location)
}
But won't this single Kotlin file in an otherwise Java-only SDK negatively affect the customers who don't use Kotlin? Can the same be expressed in Java?
Or maybe I should simply convert MyDevice.java to Kotlin? What will be negative effects of such step for the customers who are still on Java?
The problem you described is a lack of meta data Kotlin need to treat static methods as Class extension properties of extension functions.
Together with issue KT-11968 it makes it not possible for now, at least.
The best possible option is API conversion to Kotlin with a support of #JvmStaic/#JvmField and #JvmDefault where necessary for backward compatibility.
interface MyDevice {
companion object {
// nullable type or explicit init
var location: Location?
#JvmStatic get
#JvmStatic set
// kotlin
val x = MyDevice.location
MyDevice.location = x
// java
var x = MyDevice.getLocation();
MyDevice.setLocation(x);
In Kotlin, in order to achieve the same result as static methods in Java interfaces you should use a companion object to declare your static methods. Example:
interface MyDevice {
// instance methods
companion object {
// static methods
#JvmStatic
fun setLocation(location: Location) {...}
#JvmStatic
fun getLocation(): Location {...}
}
}
Note the #JvmStatic annotation. When you're calling those Kotlin functions from a Java class they will be interpreted as static methods. Example:
public void myJavaMethod() {
Location location = MyDevice.getLocation();
}
There are few solution provided by kotlin lang, there we can use to make it simple with your case. It is the nature of kotlin to make better work between Java, for me I didn't see any drawback of using Companion/Object to create the static method similar to Java. The kotlin language itself also provide many convenient helper for developer for the simplicity. As below what we can apply:
Object
object MyDevice {
#JvmStatic
fun getLocation(): Location {
}
#JvmStatic
fun setLocation(location: Location) {
}
}
Companion
class MyDevice {
companion object {
#JvmStatic
fun getLocation(): Location {
}
#JvmStatic
fun setLocation(location: Location) {
}
}
}
Call in Java:
MyDevice.setLocation(location);
final Location location = MyDevice.getLocation();
Having read the answers of the experts, having studied the links they provided, and having decompiled the Kotlin code of the wrapper class and analyzed a demo app (pure Java) which used the Kotlin-wrapped library, I decided to change the Java API.
Now I have a class with a public static object:
public class MyDevice {
public static MyDevice myDevice;
public void setLocation(Location location) {…}
public Location getLocation() {…}
}
now the Java consumers will use
import static com.example.sdk.MyDevice.myDevice;
Kotlin consumers don't need that static:
import com.example.sdk.MyDevice.myDevice
So, I don't need a separate Kotlin flavor of my library!
Related
I am seeing the following error
Platform declaration clash: The following declarations have the same
JVM signature (getHosts()Landroidx/lifecycle/MutableLiveData;):
private final fun <get-hosts>(): MutableLiveData<List> defined
in com.example.xx.viewmodel.HostsViewModel public final fun
getHosts(): MutableLiveData<List> defined in
com.example.xx.viewmodel.HostsViewModel
What am I doing wrong?
class HostsViewModel : ViewModel() {
private val hostsService = HostsService()
private val hosts: MutableLiveData<List<Host>> by lazy {
MutableLiveData<List<Host>>().also {
loadHosts()
}
}
fun getHosts(): MutableLiveData<List<Host>> {
return hosts
}
private fun loadHosts(){
hosts.value = hostsService.getHosts().body()
}
}
For every class property (val), Kotlin generates a getter called getHosts() and for var also a setter called setHosts(MutableLiveData<List<Host>> value) as per Java's convention. It hides it from the Kotlin user as getters and setters are usually just boilerplate code without offering much value. As such, your own getHosts() method clashes with the generated method at compilation. You have multiple possibilities to solve this issue:
Rename private val hosts to something else, e.g. private val internalHosts
Annotate the getHosts method with #JvmName("getHosts2"). If you do that though, consider the possibility that someone might call your code from Java and in that case, the caller would need to call getHosts2() in Java code, which might not be such nice API-design.
Reconsider your api design. In your case, you could simply make val hosts public and remove your getHosts() entirely, as the compiler will auto-generate getHosts() for you.
In addition to that, you might want to consider not exposing MutableLiveData in general as mentioned in the comments.
Edit:
Also, I would recommend that you do this:
val hosts: MutableLiveData<List<Host>> by lazy {
MutableLiveData<List<Host>>().also {
it.value = hostsService.getHosts().body()
}
}
and remove loadHosts to make your code more concise.
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.
I'm trying to define a StringDef in kotlin:
#Retention(AnnotationRetention.SOURCE)
#StringDef(NORTH, SOUTH)
annotation class FilterType {
companion object {
const val NORTH = "NORTH"
const val SOUTH = "SOUTH"
}
}
I think something is wrong in the code above.
// I can send anything to this method, when using my kotlin stringDef
private fun takeString(#DirectionJava.Direction filterType: String) {
I want the kotlin equivalent of the java below:
public class DirectionJava {
public static final String NORTH = "NORTH";
public static final String SOUTH = "SOUTH";
#Retention(RetentionPolicy.SOURCE)
#StringDef({
NORTH,
SOUTH,
})
public #interface Direction {
}
}
Calling the java defined StringDef works from kotlin
// This works as expected, the Java-written string def
// restricts what I can pass to this method
private fun takeString(#DirectionJava.Direction filterType: String) {
Where have I gone wrong, how do you define a StringDef in Kotlin?
According to jetbrains issue, Lint check plugin for enumerated annotations in kotlin is under development and is not stable yet. Checking android support annotations such as #Nullable, #StringRes, #DrawableRes, #IntRange, ... (which are written in java) works fine and user defined enumerated annotations are not checked properly. So, it seems that we should define them in java then use in kotlin.
#StringDef now works if you define it inside a companion object. See:
https://stackoverflow.com/a/70672074/2465264
Also, consider using a Kotlin enum class instead since the performance issues have been fixed in ART (Android Runtime Machine), which most Android devices are now running.
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}
Let's say we have the following extension function:
class Helper {
companion object {
fun Int.plus(value: String) = Integer.valueOf(value).plus(this)
}
}
How can you access the plus extension function from the Helper class in another class. Is there a way where we can do something like this for instance:
class OtherClass {
fun someMethod() {
val eight = 7.Helper.Companion.plus("1")
}
}
In your example Int.plus(value: String) is a member function of the Helper.Companion object (the fact that it is a companion object or that it is inside another class does not matter). This case is described in the Declaring Extensions as Members section of the documentation.
In short, to access a function with two receivers (an extension receiver of type Int and a dispatch receiver of type Helper.Companion) you have to have them both in the scope.
This can be achieved in a number of ways:
with(Helper.Companion) {
239.plus("")
}
or
with(Helper.Companion) {
with(239) {
plus("")
}
}
P.S. Putting an extension function into a companion object is very irregular and not idiomatic. I can hardly imagine why you would need that.
An extension declared like this is a member extension function, and is only going to be visible within the Helper class. If you need to access it outside of that class, put it in a wider scope, for example, make it a top level function. Alternatively, you could make it a regular function that takes two parameters, if you want to keep it within a class.
As an additional hint, you can mark this function an operator if you want to use it with the + symbol:
operator fun Int.plus(value: String) = Integer.valueOf(value) + this
val x = 2 + "25"