Utils class in Kotlin - kotlin

In Java, we can create an utilities class like this:
final class Utils {
public static boolean foo() {
return false;
}
}
But how to do this in Kotlin?
I try using functions inside object:
object Utils {
fun foo(): Boolean {
return false
}
}
But when call this method from Java code it need to add INSTANCE. Ex: Utils.INSTANCE.foo().
Then I change to declare it as top-level function (without class or object):
#file:JvmName("Utils")
#file:JvmMultifileClass
fun foo(): Boolean {
return true
}
Then I can call Utils.foo() from Java code. But from Kotlin code I got Unresolved reference compiler error. It only allow be to use foo() function directly (without Utils prefix).
So what is the best approach for declaring utils class in Kotlin?

The last solution you've proposed is actually quite idiomatic in Kotlin - there's no need to scope your function inside anything, top level functions are just fine to use for utilities, in fact, that's what most of the standard library consists of.
You've used the #JvmName annotation the right way too, that's exactly how you're supposed to make these top level functions easily callable for Java users.
Note that you only need #JvmMultifileClass if you are putting your top level functions in different files but still want them to end up grouped in the same class file (again, only for Java users). If you only have one file, or you're giving different names per file, you don't need this annotation.
If for some reason you want the same Utils.foo() syntax in both Java and Kotlin, the solution with an object and then #JvmStatic per method is the way to do that, as already shown by #marianosimone in this answer.

You'd need to use #JvmStatic for that:
In Kotlin:
object Utils {
#JvmStatic
fun foo(): Boolean = true
}
val test = Utils.foo()
In Java:
final boolean test = Utils.foo()

Note that the util class you used in Java was the only way to supply additional functions there, for anything that did not belong to a particular type or object. Using object for that in Kotlin does not make any sense. It isn't a singleton, right?
The second approach you mentioned is rather the way to go for utility functions. Internally such functions get translated to static ones and as you can see they become the static util classes in Java you are searching for, as you can't have standalone functions in Java without a class or enum. In Kotlin itself however they are just functions.
Some even count utility classes to the anti-patterns. Functions on the other hand make totally sense without a class or object whose name hasn't so much meaning anyway.

Related

Differenence between ways to declare functions in Kotlin

I have seen some code declaring functions as seen below. What is the difference between fun1 and fun2?
interface Test {
fun fun1() : Boolean = false
}
fun Test.fun2() : Boolean = true
fun1 defined inside the interface describes an open function that any implementer of the interface can override. Since it also defines a default implementation by returning something, it is not abstract and implementing classes can choose not to override it.
fun2 is an extension function. When these are used with interfaces, often the reason is to discourage overriding. An extension function cannot be overridden, but it can be hidden by another extension function with the same signature, but only in a specific scope. Therefore, some implementer of Test in another module that passes its instance back to this module cannot change the functionality of fun2 as used in this module.
The second version is an extension function.
The difference is that extension functions can be applied to any type (even outside of your code), but they do not have access to private members of that type. They are pretty much the same as calling function with this type as a first parameter, just nicer syntax

Kotlin equivalent of class properties, constructors, empty parameter constructors, getters and setters

I am currently practicing in developing kotlin and as of now I seem to get confused with kotlin's class structure.
this is a code in java
//properties
private String var;
//constructor
public SampleClass(String var){
this.var = var;
}
public SampleClass(){
}
//getters and setters
public String getVar(){
return this.var;
}
public String setVar(String var){
this.var = var;
}
what's the kotlin equivalent of this ?
This is the equivalent Kotlin code for your Java code:
class SampleClass(var `var`: String? = null)
There are a few things to note:
Your Java snippet above omits the wrapping class SampleClass code
Your setVar() indicates that it returns a String, but it's actually void. I assume you intended for it to have a void return type.
Your property var is not ideal for Kotlin, because it's a reserved word. That's why we have to escape it with backticks. (It could also be kind of confusing in Java 10, since var is a reserved type name there now).
Here's why this one-liner is equivalent to the Java listing.
The constructor part - the part between the parentheses - can be used to accept constructor arguments, but by putting the Kotlin keyword var at the beginning, we tell Kotlin that we want this to also be a property. Kotlin will create a getter and setter for it.
The String? part makes this property of type nullable String.
Instead of creating two different constructors, we just give our var property argument a default value of null by using = null. When creating this class from Java, it'll still show up as two constructors.
If you're using IntelliJ or Android Studio, you can tell it to convert any Java class to Kotlin. Just open the class file, and go to the Code menu, and choose Convert Java file to Kotlin file. It won't necessarily generate very idiomatic code (e.g., it might create two constructors instead of using a default for the constructor argument), but it'll get you started.
For "what is Kotlin equivalent of some code in Java", there is an universal answer: copy the Java code and paste it into a Kotlin file in IDEA/Android Studio. Or convert the entire file.
On the web, you can use https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Java%20to%20Kotlin%20conversion/Task.kt.

Kotlin extension functions vs member functions?

I am aware that extension functions are used in Kotlin to extend the functionality of a class (for example, one from a library or API).
However, is there any advantage, in terms of code readability/structure, by using extension functions:
class Foo { ... }
fun Foo.bar() {
// Some stuff
}
As opposed to member functions:
class Foo {
...
fun bar() {
// Some stuff
}
}
?
Is there a recommended practice?
When to use member functions
You should use member functions if all of the following apply:
The code is written originally in Kotlin
You can modify the code
The method makes sense to be able to use from any other code
When to use extension functions
You should use extension functions if any of the following apply:
The code was originally written in Java and you want to add methods written in Kotlin
You cannot change the original code
You want a special function that only makes sense for a particular part of the code
Why?
Generally, member functions are easier to find than extension functions, as they are guaranteed to be in the class they are a member of (or a super class/interface).
They also do not need to be imported into all of the code that uses them.
From my point of view, there are two compelling reasons to use extension functions:
To "extend" the behaviour of a class you're not the author of / can't change (and where inheritance doesn't make sense or isn't possible).
To provide a scope for particular functionality. For example, an extension function may be declared as a freestanding function, in which case it's usable everywhere. Or you may choose to declare it as a (private) member function of another class, in which case it's only usable from inside that class.
It sounds like #1 isn't a concern in your case, so it's really more down to #2.
Extension functions are similar to those you create as a utility functions.
A basic example would be something like this:
// Strings.kt
fun String.isEmail() : Boolean {
// check for email pattern and return true/false
}
This code can be written as a utility function in Java like this:
class StringUtils {
public static boolean isEmail(String email) {
// check for email pattern and return true/false
}
}
So what it essentially does is, calling the same function with the object you call on will be passed as the first parameter to the argument. Like the same function I have given example of in Java.
If you want to call the extension function created in kotlin from java, you need to pass the caller as the first argument. Like,
StringsKt.isEmail("example#example.com")
As per the documentation,
Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type.
They are simply static functions with the caller as the first argument and other parameters followed by it. It just extends the ability for us to write it that way.
When to create extension functions?
When you don't have access to that class. When that class belongs to some library you have not created.
For primitive types. Int, Float, String, etc.
The another reason for using extension function is, you don't have to extend that class in order to use the methods, as if they belong to that class (but not actually part of that class).
Hope it makes a bit clear for you..
As mentioned in other answers, extension functions are primarily used in code that you can't change - maybe you want to change complex expression around some library object into easier and more readable expression.
My take would be to use extension functions for data classes. My reasoning is purely philosophical, data classes should be used only as data carriers, they shouldn't carry state and by themselves shouldn't do anything. That's why I think you should use extension function in case you need to write a function around data class.

Kotlin - How i can access my new class extension function from another file

I am very new to Kotlin.
I want to be able to add a function to my abstract class, so when I define that function I will be able to invoke that on every child from that class(they inherit the abstract class)
However,I want to define those extension functions in other file.
I can't access those functions when i try to invoke them on a particular child implementation of the abstract class.
What are the rules, that I need to made to resolve my problem?
I want to by able achieve something like this:
abstract class Parent(val val1, val val2, val val3){}
class Child(var val1, var val2, var val3) : Parent(val1, val2, val3){}
class Child2(var val1, var val2, var val3) : Parent(val1, val2, val3){}
The extension method for parent and all childs:
fun Parent.convertToChild2( ): Child2? {
return //some creation method of Child2
}
And I want to be able to invoke this:
child: Child
child.convertToChild2
I defined all classes in separate file and also the extension function in other file.
I cannot access the function like this - is not visible.
The answer for my question, that satisfies me is just to extract the method to some "object" structure in other file and whenever we want to access that function we must import the path(package.object.method) to this.
But the problem is, that IDE is not propose me the path to my extension function - i must import it by myself.
I am using Android Studio 3 preview, hope this will be fixed.
UPDATE
It is better to define those function in just plain Kotlin file, so the functions will be not owned by any structure. Then it will be not a problem with importing those automatically by IDE from any place.
I believe that there is a misunderstanding here about extension functions. Extension functions are regular static functions that take in an instance of the receiver class as a parameter implicitly when you define the function and operate on it.
These static functions (aka extension functions) have some limitations.
They are not added to the class hierarchy so subclasses can not inherit them (if you define extension function for parent class you can't expect that method to be present in child class)
They don't have access to the private properties of the class that they are extending.
Also, they are resolved statically, for example (taken from here)
open class Shape
class Rectangle: Shape()
fun Shape.getName() = "Shape"
fun Rectangle.getName() = "Rectangle"
fun printClassName(s: Shape) {
println(s.getName())
}
printClassName(Rectangle())
This example prints "Shape", because the extension function being called depends only on the declared type of the parameter s, which is the Shape class.
First of all: There a many errors in your source code, you should fix before asking the question here (missing type annotations in constructors, missing val/var etc.).
To your question:
Normally, you can access extension functions even if defined in different kt files. Read the official docs covering extension scopes.
It's important to import your extension function
There is a way to do that:
fun <T: Parent> T.toChild2() {
TODO()
}
Child(...).toChild2()

Android Kotlin Extension super calling

i am a Java Android Developer and i'm approaching to Kotlin
I have defined the following class:
open class Player : RealmObject() {
...
}
And i defined the following two extensions, one for the generic RealmObject class and one for the specific Player class:
fun RealmObject.store() {
Realm.getDefaultInstance().use { realm ->
realm.beginTransaction()
realm.copyToRealmOrUpdate(this)
realm.commitTransaction()
}
}
fun Player.store(){
this.loggedAt = Date()
(this as RealmObject).store()
}
What i want is if i call .store() on any RealmObject object, the RelamObject.store() extension will be called BUT if i call .store() on a Player instance the extension that will be called will be Player.store().
(No problem for now)
I don't want to copy paste the same code, i love to write less reuse more.
So i need that internally the Player.store() will call the generic RealmObject.store()
I got it. The code i wrote up there is actually working as expected :D
What i am asking is (just because i wrote that just by personally intuition):
Is this the good way?! Or there is some better way?
Thank you
Your approach seems to be perfectly correct, because it does exactly what is needed. Kotlin resolves the extension calls based on the static (inferred or declared) type of the receiver expression, and the cast (this as RealmObject) makes the static expression type RealmObject.
Another valid way to do this, which I'm not sure is better, is to use a callable reference to the other extension:
fun Player.store(){
this.loggedAt = Date()
(RealmObject::store)(this)
}