I want to have functions that sit in classes (not polluting the global namespace) but are accessed statically (never creating an object in which they reside).
Proposed solution:
object A {
#JvmStatic
fun mkdir() {}
}
Is this a good solution or will it inevitably create an object? Which pattern should I use?
Unfortunately, there's currently no way to create a static function on a class in Kotlin that doesn't result in the instantiation of an Object (the companion object). You'll have to write it in Java and call it from Kotlin if you want to do this.
The #JvmStatic annotation creates a static method in the JVM bytecode, but all that does is retrieve the instance of the companion object and call the method on it, which you can verify by decompiling the resulting bytecode.
Related
In an interview I was told to write a Singleton class so I wrote the following code
object Ant{
}
but later he asked me to write Singleton instance which confused me and I ended up writing like this
object what{
}
now, I know I am wrong but I am really curious how to write down Singleton Instance.
please check my helper class, What I was using might be wrong so please correct me
class Helper{
companion object{
#Volatile
var INSTANCE : Helper? = null
fun getInstance(): Helper {
return INSTANCE?: synchronized(this){
val instance = Helper()
INSTANCE = instance
instance
}
}
}
}
and then I would create a variable like this val helper = Helper.getInstance() and use this object from then on, sometimes I declare them as global variables outside class to make it easier to access across the app
recently we have shifted to Koin so we just declare these classes as singleton by using #Single ksp annotation
It is hard to guess what an interviewer was asking about, after the event, but in your code above there is no instance of either Ant or What yet, only the object declaration. You would need to instantiate the object like:
val mySingleton = What
Object declarations are initialized lazily when first used
I think you were right!
In Kotlin, an object is a singleton: it defines a class, with exactly one instance. (That one instance is created automatically, and you can't create any others.) So if you need a singleton, that's the standard way to get it.
You could do something like:
class Ant private constructor() {
companion object {
val INSTANCE = Ant()
}
}
That's how you'd have to do it in Java: a private constructor and a single static instance. It may be that your interviewer was more familiar with Java, and was expecting you to do that — but that's absolutely pointless in Kotlin, because object does exactly the same, only more concisely (and with less opportunity for errors or race conditions or whatever).
If you were using a framework such as Spring, that provides other ways of creating single instances (e.g. with annotations such as #Component, #Bean, etc.) but those are specific to the framework, so you'd probably know if you needed anything like that.
Or your interviewer may have something else in mind — but in that case, he should have given you some hints; you're not a mind-reader!
The bottom line is that without any further information, object is the most obvious way to get a singleton, so from what you've posted, you were right.
Is it a good idea to cut my code anywhere around the project in other classes using extension functions?
I mean what is the point?For what exactly a class fun can leak to other classes?
Friends, I'm new to Kotlin and I appreciate if anyone can provide a real example of using extension fun in kotlin.
class Car{
//any code you imagine
}
class Garage{
//any code
fun Car.boost(){
//boost implementation
}
}
As stated in Kotlin Coding Conventions, extension functions are a good practice:
Use extension functions liberally. Every time you have a function that
works primarily on an object, consider making it an extension function
accepting that object as a receiver.
There are a few reasons for that:
Extension functions keep your class small and easy to reason about
Extension functions force you to have good API, since they cannot access any private members of your class
Extension functions have zero cost on performance, since they're simply rewritten by Kotlin compiler into static methods, with method receiver (the class you're extending) as its first argument
I'm wondering what is the best way to structure functional code in Kotlin.
I don't want to create unnecessary objects (and put functions in a closed scope) to group my functions with. I heard I can group functions by packages and put them in the top level of a package. I've also seen in Arrow library that functions are grouped in interface companion objects as extension functions and this looks the best except the fact I need to create a companion object.
Object way:
object Container {
fun myFunc() = ...
}
...
Container.myFunc()
Package way:
package myPackage
fun myFunc() = ...
...
myPackage.myFunc()
Arrow way:
interface Container {
companion object {
fun Container.myfunc() = ...
}
}
...
Container.myFunc()
What is the best way to structure my functions and group them using Kotlin? I want to keep a pure functional style, avoid creating any sort of objects, and be able to easily navigate to functions by namespaces like:
Person.Repository.getById(id: UUID)
If I understand you correctly, you're looking for the concept of namespaces (structured hierarchical scope for accessing symbols).
Kotlin does not support namespaces, but as you found out, there are different ways of having similar functionality:
object declarations. They pretty much fulfill the needs, however they lead to creation of an actual object in JVM and introduce a new type, which you don't need. The Jetbrains team generally discouraged the use of objects as namespaces, but it's of course still an option. I don't see how companion objects inside interfaces add any value. Maybe the idea is to limit the scope to classes which implement the interface.
Top-level functions. While possible, top-level functions in Kotlin pollute the global namespace, and the call-site does not let you specify where they belong. You could of course do workarounds, but all of them are rather ugly:
Fully qualify the package com.acme.project.myFunc()
Use a deliberately short, but no longer domain-representing package functional.myFunc()
Call function without package, but with prefix package_myFunc()
Extension functions. If the functionality is closely related to the objects it's operating on, extension functions are a good option. You see this for the Kotlin standard collections and all their functional algorithms like map(), filter(), fold() etc.
Global variables. This does not add much over the object approach, just prevents you from introducing a named type. The idea is to create an anymous object implementing one or more interfaces (unfortunately, without interfaces the declared functions are not globally accessible):
interface Functionals {
fun func(): Int
}
val globals = object : Functionals {
override fun func() = 3
}
It is mainly handy if your object implements different interfaces, so that you can pass only a part of the functionality to different modules. Note that the same can be achieved with objects alone, as they can implement interfaces too.
I have noticed that we can create classes in Kotlin without curly braces like below.
//Example classFile.kt
class Empty
class SecondEmpty
fun firstMethod() {
}
My question is, why we need such feature? in which situation we can use this?
In the above example, I have written a method called firstMethod() how can I call that from the other objects?
Empty classes have been discussed in What is the purpose of empty class in Kotlin? already.
Regarding your firstMethod: in Kotlin, we have so called top-level functions. These can be defined in any file without an enclosing class. Another example for this is main which is defined top-level in most cases.
How to call top-level functions?
You can simply import the function into other files and call them. For instance, if firstMethod were defined in com/x/Example.kt (package com.x), you may import com.x.firstMethod in other Kotlin files and call that method.
For Java, it’s important to know, that top-level functions are compiled into a class as static members. As for the example above, you can call com.x.ExampleKt.firstMethod from Java.
I am currently learning the Kotlin language.
I want to know what is a Companion Object, and why do we need it?
I think there is a similar concept in Scala.
Members of the companion object can be called by using simply the class name as the qualifier
like a java static
if called Anothrer class's member variable or method
you use that companion object