search
HomeJavajavaTutorialSummary of Kotlin syntax learning--variable definition, function expansion, Parcelable serialization

This article mainly introduces Kotlin grammar learning-variable definition, function expansion, Parcelable serialization and other briefly summarized related information. Friends in need can refer to

Kotlin grammar learning-variable definition , function extension, Parcelable serialization, etc. A brief summary

At this year’s Google I/O 2017 Developer Conference, Google announced that it would officially include Kotlin as the official first-level development language for Android programs. (First-class language), as an Android developer, of course, you must gradually become familiar with this language, and the first step is to learn the grammar.

Before this, we need to understand how to use Kotlin to write an Android application. For Android Studio 3.0 version, we can directly check the Include Kotlin support option when creating the project; for versions before 3.0, we need to install the Kotlin plug-in and manually configure gradle as follows.

Add the following code under the gradle of the app

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

Add the following code under the gradle of the project

ext.kotlin_version = '1.1.2-3'

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

Kotlin defines variables

  1. There are two types of variable definitions in kotlin, val and var, where val is equivalent to the final modified variable in Java (read-only), which is usually a constant, and var is usually a variable.

  2. Kotlin's variable definition supports type inference during assignment, and all variables are modified to "not null" by default. You must explicitly add the ? modifier after the type before assigning it to null. .

  3. When we write code, we should try our best to habitually design variables to be non-nullable, so that many problems will be reduced in subsequent operations on the variables.

Kotlin function extension

The specific syntax is fun + type.function (parameter)

 fun Context.toast(message: String, length: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, message, length).show()
  }

Kotlin Parcelable serialization

package com.john.kotlinstudy

import android.os.Parcel
import android.os.Parcelable

/**
 * Java Bean 数据实体类
 * Created by john on 17-5-24.
 */

data class UserBean(var name: String, var id: String) : Parcelable {

  constructor(source: Parcel) : this(source.readString(), source.readString())

  override fun describeContents(): Int {
    return 0
  }

  override fun writeToParcel(dest: Parcel, flags: Int) {
    dest.writeString(this.name)
    dest.writeString(this.id)
  }

  companion object {

    @JvmField val CREATOR: Parcelable.Creator<UserBean> = object : Parcelable.Creator<UserBean> {
      override fun createFromParcel(source: Parcel): UserBean {
        return UserBean(source)
      }

      override fun newArray(size: Int): Array<UserBean?> {
        return arrayOfNulls(size)
      }
    }
  }
}

companion keyword interpretation

  1. Unlike Java or C#, in Kotlin , Class does not have static methods. In most cases, it is recommended to use package-level functions instead of static methods.

  2. If you need to write a function (such as a factory function) that can access the inside of Class without instantiating it, you can declare it as a real-name Object within Class.

  3. In addition, if you declare a companion object in Class, all members in the object will be equivalent to using the static modifier in Java/C# syntax, externally These properties or functions can only be accessed through the class name.

@JvmField annotation function

  1. Instructs the Kotlin compiler not to generate getters/setters for this property and replace it Exposed as a field.

  2. If you need to expose a Kotlin property as a field in Java, you need to annotate it with the @JvmField annotation and the field will have the same visibility as the underlying property.

Writing tool classes in Kotlin

In Java, we will encapsulate some commonly used functions into tool classes. The tool class is actually Extensions to the functions of common classes such as String, Collection, IO, etc. The tool class methods and variables we write will be written static. Because we just want to call these methods without involving any attributes and variables in the tool class, so there is no need to instantiate (new). Since there is no need to instantiate, then just use static.

package com.john.kotlinstudy

import android.content.Context
import android.widget.Toast

/**
 * Toast工具类
 * Created by john on 17-5-24.
 */
object ToastUtils {

  fun toast(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
  }
}

Kotlin Activity Jump

We set the click event in MainActivity, jump to another Activity, and pass the data at the same time

package com.john.kotlinstudy

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    test_tv.text = "hello kotlin"
    test_tv.setOnClickListener {
      ToastUtils.toast(this, "hello kotlin")
      val user = UserBean("zhang", "001")
      user.id = "100"
      SecondActivity.navigateTo(this, user)
    }
  }

  fun Context.toast(message: String, length: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, message, length).show()
  }
}

Then create a new A SecondActivity provides a static method for Activity jump. Everyone must know that the advantage of doing this is that the caller knows what parameters are required without looking at the source code. If you write according to java, you will find that there is no static keyword! Don't panic, you can use companion objects to achieve this. Companion objects are objects that accompany the declaration cycle of this class.

package com.john.kotlinstudy

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_second.*

/**
 * 跳转Activity测试类
 * Created by john on 17-5-24.
 */
class SecondActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_second)
    val user = intent.getParcelableExtra<UserBean>(EXTRA_KEY_USER)
    user_name_tv.text = user.name
    ToastUtils.toast(this, user.id)
  }

  //创建一个伴生对象
  companion object {
    //extra的key
    val EXTRA_KEY_USER = "extra.user"

    fun navigateTo(context: Context, user: UserBean) {
      val intent = Intent(context, SecondActivity::class.java)
      intent.putExtra(EXTRA_KEY_USER, user)
      context.startActivity(intent)
    }
  }
}

Summary

The above is just a brief introduction to some grammatical features of kotlin, which is considered an introduction. It can eliminate some unfamiliarity and fear of this new language. In fact, kotlin has many new features. , this still requires us to slowly digest and understand it during development.

【Related Recommendations】

1. JavaScript implementation method to determine variable type based on custom function

2. Details in Java How to create objects

3. A brief introduction to several java objects

The above is the detailed content of Summary of Kotlin syntax learning--variable definition, function expansion, Parcelable serialization. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor