Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

A static method

To define static methods in Java, you simply add static before the method.

There are four methods in Kotlin: object singleton, Companion Object (which can write static methods locally), JvmStatic annotations, and top-level functions.

1.1 the object

Classes decorated with object, which are actually singletons, are called by the class name and method directly in Kotlin.

object Util {
    fun doAction(a){
        Log.v("TAG"."doAction")}}/ / in the kotlin calls
Util.doAction()

// Calling INSTANCE in Java is a singleton class for Util
Util.INSTANCE.doAction();
Copy the code

1.2 companion object

Methods modified with the Companion Object can also be added by class name. Directly, but in this case through the companion object. It works by creating a companion class in the original class, and Kotlin guarantees that the companion class has only one object.

class Util{
    // This is where the singleton class can be called
    companion object {
        fun doAction(a){
            Log.v("TAG"."doAction")}}// Here is the normal method
    fun doAction2(a){
        Log.v("TAG"."doAction")}}/ / kotlin calls
Util.doAction()

// Java calls, Companion is a singleton class
Util.Companion.doAction();
Copy the code

1.3 @ JvmStatic annotation

Annotate the methods of a singleton class (object) and associated objects with @jVMStatic, and the compiler compiles these methods into true static methods.

Note: JvmStatic can only be commented on methods in singleton classes or Companion Objects.

class Util{
    // This is where the singleton class can be called
    companion object {
        @JvmStatic
        fun doAction(a){
            Log.v("TAG"."doAction")}}// Here is the normal method
    fun doAction2(a){
        Log.v("TAG"."doAction")}}// call in kotlin
Util.doAction()
 
// Calls in Java become true singleton classes
Util.doAction();
Copy the code

1.4 Top-level Method

Top-level functions are those that are not defined in any class. Just write them on the outer layer of any class. Kotlin compiles all top-level functions into static methods that can be called directly from anywhere.

// Outside the class
fun doAction(a){}class Util {}// Kotlin call method
doAction()
 
// Java call method, true static method
UtilKt.doAction();
Copy the code

Infix function

The infix function modifies the syntax of function calls.

For example, A to B is equal to a.dot (B).

How to do it: Add infix in front of the function.

Restrictions: 1. Cannot be a top-level function; 2. 2. Only one parameter can be configured.

Example:

infix fun String.beginsWith(p:String) = startsWith(p)
Copy the code

Simplify common apis with higher-order functions

The apply function simplifies intent.putextra ():

 fun SharedPreferences.open(block: SharedPreferences.Editor. () - >Unit) {
        valEditor = edit() editor.block() editor.apply()}"user", Context.MODE_PRIVATE).open {
            putString("username"."Lucas")
            putBoolean("graduated".false)}Copy the code

Simplify the SharedPreferences:

 fun SharedPreferences.open(block: SharedPreferences.Editor. () - >Unit) {
        valEditor = edit() editor.block() editor.apply()}"user", Context.MODE_PRIVATE).open {
            putString("username"."Lucas")
            putBoolean("graduated".false)}Copy the code

Simplify the ContentValues:

fun cvOf(vararg pairs: Pair<String, Any? >) =  ContentValues().apply {
        for(pair in pairs){
            val key = pair.first
            val value = pair.second
            when(value){
                is Int -> put(key, value)
                is Long -> put(key, value)
                is Short -> put(key, value)
                is Float -> put(key, value)
                is Double -> put(key, value)
                is Boolean -> put(key, value)
                is String -> put(key, value)
                is Byte -> put(key, value)
                is ByteArray -> put(key, value)
                null -> putNull(key)
            }
        }
    }
Copy the code

The lazy loading technique implements lazy():

  fun <T> later(block: () -> T) = Later(block)
 
    class Later<T>(val block: () -> T){
        var value: Any? = null
 
        operator fun getValue(any: Any? , prop:KProperty< * >): T{
            if (value == null){
                value = block
            }
            return value asT}} use:val haha:String by later {
        "hhaa"
    }
Copy the code

Generic implementations simplify startActivity() with an intent pass:

    inline fun <reified T> startActivity(context: Context, block: Intent. () - >Unit){
        val intent = Intent(context, T::class.java) intent.block() context.startActivity(intent)}this){
        putExtra("haha"."1111")
        putExtra("hahaaaa"."1111")}Copy the code

The maximum value and minimum value of the simplified N number:

   fun <T : Comparator<T>> MyMax(vararg nums: T): T{
        if (nums.isEmpty()) throw RuntimeException("params can not be empty")
        var maxNum = nums[0]
        for (num in nums){
            if (num > maxNum){
                maxNum = num
            }
        }
        returnMaxNum} uses:val a = 1
        val b = 3
        val c = 2
        val largest = MyMax(a,b,c)
Copy the code

Simplify the Toast:

    fun String.showToast(context: Context, duration: Int = Toast.LENGTH_SHORT){
        Toast.makeText(context, this, duration).show()
    }
    fun Int.showToast(context: Context, duration: Int = Toast.LENGTH_SHORT){
        Toast.makeText(context, this, duration).show()}"ahah".showToast(this, Toast.LENGTH_LONG)
Copy the code

Simplify the Snackbar:

fun View.showSnackbar(text: String, actionText: String? =null, duration: Int = Snackbar.LENGTH_SHORT, block: (() -> Unit)? =null){
        val snackbar = Snackbar.make(this, text, duration)
        if(actionText ! =null&& block ! =null){
            snackbar.setAction(actionText){
                block()
            }
        }
        snackbar.show()
    }
 
    fun View.showSnackbar(text: String, actionResId: Int? =null, duration: Int = Snackbar.LENGTH_SHORT, block: (() -> Unit)? =null){
        val snackbar = Snackbar.make(this, text, duration)
        if(actionResId ! =null&& block ! =null){
            snackbar.setAction(actionResId){
                block()
            }
        }
        snackbar.show()
    }
Copy the code