milad salimi
milad salimi

Reputation: 1660

Define common functions in kotlin

For define Util(common functions) we can use 3 approach :

First :

We can define a File and add function to it like this :

fun func1(): String {
    return "x"
}

fun func2(): String {
    return "y"
}

Then we can use this in every where like this :

fileName.func1()

Second :

We can define a class and add these functions to class like this :

class Util{
fun func1(): String {
    return "x"
}

fun func2(): String {
    return "y"
}
}

we can inject it and use this like :

 private val mUtil: Util by inject()

mutil.func1()

Third:

We can define an object like this :

object Util{
fun func1(): String {
    return "x"
}

fun func2(): String {
    return "y"
}

Then we can use this like :

Util.func1()

suppose that we have reusable fun that it use in different class , activity or fragment now is better to use first , second or third ?

Upvotes: 0

Views: 1356

Answers (2)

Taki
Taki

Reputation: 3730

According to my understanding :

  • In the first example, we simply define a function to be used within the scope of component (could be a fragment or an activity ..)

  • In the second example, which I think more used in Java than Kotlin, you simply create a class in which you define some static variable or function to be accessed in your components later

  • Example 3, I have no idea as I never used that

Upvotes: 1

GHH
GHH

Reputation: 2019

first one is static function

second one is normal function

third is singleton function

you can decomplie to see the java code and see their differs.

Kotlin file

fun fun1() {}

class TestClass {

    fun testFun() {}
}

object ObjectClass {

    fun objectFun() {}
}

Java file


public final class TTTKt {
   public static final void fun1() {
   }
}

public final class TestClass {
   public final void testFun() {
   }
}

public final class ObjectClass {
   public static final ObjectClass INSTANCE;

   public final void objectFun() {
   }

   private ObjectClass() {
   }

   static {
      ObjectClass var0 = new ObjectClass();
      INSTANCE = var0;
   }
}

Upvotes: 0

Related Questions