Use Kotlin in Android

1. Environmental requirements

  • Use Android Studio 3.0 or higher
  • Kotlin plugin installed

2. Place Kotlin

In Android Studio, select Tools> Kotlin> Configure Kotlin in Project. If a window titled Choose Configurator appears, select Android with Gradle and make sure to select All modules, then click OK.
Android Studio will add the required dependencies in the build.gradle file at the app level and the project level.

3. Convert Java files to Kotlin

选择 Code > Convert Java File to Kotlin File

4. A Kotlin version of the JavaBean class

Java version

class Contact {
    
    

    private String firstName;
    private String lastName;
    private String email;


    Contact(String firstName, String lastName, String email) {
    
    
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    String getFirstName() {
    
    
        return firstName;
    }

    String getLastName() {
    
    
        return lastName;
    }

    String getEmail() {
    
    
        return email;
    }

    void setEmail(String email) {
    
    
        this.email = email;
    }
}

Kotlin version

internal class Contact(val firstName: String, val lastName: String, var email: String?)
  • Declare a class named Contact.
  • Declare three attributes for this class: declare two read-only fields for the first name and last name, and declare a variable variable for the email address.
  • The firstName and lastName properties are guaranteed to never be null because their type is String.
  • The email field can be null because its type is String?

  1. In Kotlin, use the var keyword to declare as mutable, or use the val keyword to declare as immutable. Variable attributes (declared with var) can be assigned any number of times, while immutable variables (declared with val) can only be assigned once.

  2. The Kotlin attribute type follows the attribute name and colon: val firstName: String.

  3. The main constructor is part of the class declaration: it immediately follows the class name, in parentheses. You can use the constructor keyword in the body of the class to provide other constructors. The attributes are declared in the main constructor.

  4. By default, the attribute type in Kotlin must not be null. If the property can retain a null value, use the? Syntax to declare it with a nullable type. For example, String? can be null, but String cannot.

5. data keyword

The data keyword can tell the Kotlin compiler class to store data, which will generate a lot of useful functions.
For example: the toString() implementation that reveals the content of the object, the copy() function, and the component function to deconstruct the object into fields.

internal data class Contact
(val firstName: String, val lastName: String, var email: String?)

The above code, after adding the data keyword, will call the toString method when printing the Contact class and print out the value of each attribute inside.
If you don't add it, just print the address of the object.

Kotlin tips:

  1. The semicolon at the end of the statement is optional in Kotlin.
  2. The function is declared by the fun keyword.
  3. With the lateinit keyword, you can postpone the initialization of non-null variables.
  4. If the attribute type is not ambiguous, it can be ignored. For example, the
    private var mEntryValid:Boolean = falseignore type becomes:private var mEntryValid = false
  5. You can use the !! operator to access fields and functions that can be of type null. This tells the compiler that you know that the reference will not be null when it is called. Please use this operator with caution, as it may cause a NullPointerException.

6. for loop

The first type is ..left closed and right closed

for (i in 0..contactsJson.length() - 1)

The second type is untilleft closed and right open

for (i in 0 until contactsJson.length())

7. String interpolation

val fullName = "$firstName $lastName"

The values ​​of the firstName and lastName variables are quoted, and they are assigned to the fullName variable after splicing.

8. Kotlin Android extension view binding

No need to findViewById anymore~

  1. Apply the Kotlin Android extension plugin in your app-level build.gradle file to use Kotlin view binding.
    To do: in application-level add code to the beginning of the file build.gradleapply plugin: 'kotlin-android-extensions'
  2. Any control in the layout can be used directly, and the variable name that uses it is the ID of the control.
  3. Refers to a view that is a child of another extended view (for example, ViewHolder or the root view of a dialog box). In this case, the syntax when using it is<rootview>.id

9. Using lambda expressions

Kotlin provides support for lambdas, which are functions that are not declared but are immediately passed as expressions. They have the following syntax:

  • Lambda expressions are always surrounded by curly braces {}.
  • The arrow (->) separates the function parameters from the function definition.
  • The parameters of the function (if any) are declared before ->. If it can be inferred, the parameter type can be ignored.
  • The body of the function is defined after ->.
{
    
     x: Int, y: Int -> x + y }

Create an immutable variable that stores a lambda expression named notEmpty. This lambda expression takes TextView as a parameter (EditText inherits from TextView) and returns a Boolean value

val notEmpty: (TextView) -> Boolean

Use the Kotlin isNotEmpty() function to assign a lambda expression to notEmpty, which will return true when the text property of the TextView is not empty:

val notEmpty: (TextView) -> Boolean = {
    
     textView -> textView.text.isNotEmpty() }

If the lambda expression has only one parameter, it can be ignored and replaced with the it keyword. Remove the textView parameter and replace its reference with it in the lambda body:

val notEmpty: (TextView) -> Boolean = {
    
     it.text.isNotEmpty() }

Kotlin tips:

  1. If the lambda expression has only one parameter, it can be inferred using the it keyword.
  2. Kotlin does not have ternary operators, but uses if/else statements instead.

10. Kotlin Express Ternary Operator

Java Edition Ternary Operator

result = isValidate?true:false

Kotlin version, use if/else

retsult = if (isValidate) true else false

11. Use Kotlin extension functions

One of the main features of the Kotlin language is extension, which is the ability to add functionality to any external class (a class you haven't created). This helps avoid "utility" classes, which encapsulate imported Java or Android framework classes that you cannot modify. For example, if you want to add a function to ArrayList to extract any string with only integers, you can add an extension function to ArrayList so that you don't need to create any subclasses.

The standard Kotlin library contains a large number of extensions to commonly used Java classes.

11.1 Sort

The Kotlin standard library includes the sortBy() extension function for variable lists (including ArrayList). This function uses the "selector" function as a parameter. This is an example of a higher-order function, which takes another parameter as a parameter. The purpose of this incoming function is to define a natural sort order for any list of objects.
The sortBy() function will iterate through each list item that calls it, and execute the selector function on the list item to get the value it knows how to sort. The selector function usually returns a field of the object that implements the Comparable interface, such as String or Int.

Call the sortBy() function on the mContacts list. Pass in a lambda expression using the Contact object as a parameter and return its name attribute. Since the contact is the only parameter, it can be referenced as it:

mContacts.sortBy {
    
     it.firstName }

11.2 Replace the for loop with Kotlin standard library extension

The Kotlin standard library adds many extension functions to collections (such as Lists, Sets, and Maps) to convert between different collections.

Place the cursor on the for keyword. Press the orange light bulb to display the quick repair menu and select Replace with mapTo(){}.

Java version of for loop

 private ArrayList<Contact> loadContacts() {
    
    
        Set<String> contactSet = mPrefs.getStringSet
                (CONTACT_KEY, new HashSet<String>());
        ArrayList<Contact> contacts = new ArrayList<>();
        for (String contactString : contactSet) {
    
    
            contacts.add(new Gson().fromJson(contactString, Contact.class));
        }
        return contacts;
    }

The changed Kotlin version, using the mapTo function

private fun loadContacts(): ArrayList<Contact> {
    
    
    val contactSet = mPrefs.getStringSet(CONTACT_KEY, HashSet())
    return contactSet.mapTo(ArrayList<Contact>()) {
    
     
        Gson().fromJson(it, Contact::class.java) 
    }
}

Android Studio will change the for loop into a mapTo(){} function. This higher-order function takes two parameters: the collection you want to convert the receiver parameters (the class you are extending) into, and how to specify how the collection items The lambda expression converted into a list item.
Note the it notation in lambda, which represents a single incoming parameter (item in the list).

Another modification of the for loop, using the map function

Java version of the code

private void saveContacts() {
    
    
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.clear();
        HashSet<String> contactSet = new HashSet<>();
        for (Contact contact : mContacts) {
    
    
            contactSet.add(new Gson().toJson(contact));
        }
        editor.putStringSet(CONTACT_KEY, contactSet);
        editor.apply();
    }

The changed Kotlin version, using the map function

 private fun saveContacts() {
    
    
        val editor = mPrefs.edit()
        editor.clear()
        val contactSet = mContacts.map {
    
     Gson().toJson(it) }.toSet()
        editor.putStringSet(CONTACT_KEY, contactSet)
        editor.apply()
    }

Similarly, Android Studio will replace the loop with an extension function: this time it’s map{}, which can execute the incoming function on each item in the list (using GSON to convert it to a string), and then use toSet() to extend it The function converts the result into a set

Kotlin tips:

  1. The Kotlin standard library comes with a large number of extension functions that can add functionality to existing Java data structures.
  2. These extensions are usually higher-order functions that use other functions as parameters (usually passed in as lambda expressions).
    The sortBy() extension function can extend many Java list classes to sort these classes according to the incoming lambda expression. The lambda expression takes the list item as a parameter and returns an object that implements the Comparable interface, thereby defining the natural sorting of the list order.
  3. The mapTo() and map() functions are also higher-order functions that can extend Java lists. The incoming lambda expression acts on each item in the list.

Reference https://github.com/googlecodelabs/android-using-kotlin

Guess you like

Origin blog.csdn.net/fxjzzyo/article/details/106600583
Recommended