Introduction to Kotlin syntax and kotlin syntax

Source: Internet
Author: User

Introduction to Kotlin syntax and kotlin syntax
Kotlin syntax

Kotlin is toxic and addictive when used ...... A little exaggerated. It was actually used to write a demo that records POI and tracks. However, the syntax is really concise. Here, Kotlin is different from Java, or it has more concise and elegant syntax and features than Java.

1. String Template

Compared with Java String concatenation, Kotlin's string template is more compact:

fun main(args:Array
 
  ){    val name = if(args.size > 0) args[0] else "Kotlin"    println("Hello, $name!")}
 

Besides Introduction Use Change Quantity Name Name External , Also Yes To Connect Pass "Role =" presentation "> You can also use Introduction Use Change Quantity Name Name External , Also Yes To Connect Pass {} Reference more complex expressions

fun main(args:Array
 
  ){    if(args.size > 0){        println("Hello, ${args[0]}!")    }}
 

Compared with Java String concatenation, a series of +, or StringBuilder append, does the Kotlin string template look much more elegant. AndThe compiled code creates a StringBuilder object and attaches the constant part and the variable part to it, with the same efficiency.

2. a value-based Expression

In Kotlin, if is an expression, not a statement. The difference between a statement and an expression is that the expression has a value and can be used as part of another expression; the statements always enclose the top-level elements of the code block and do not have their own values. In Java, all control structures are statements, while in Kotlin, most control structures except for loops (for, do, and do/while) are expressions. This ability to combine control structures and other expressions allows you to briefly express many common patterns.
On the other hand, the value assignment operation in Java is an expression, but it turns into a statement in Kotlin. This helps avoid confusion between comparison and assignment, which is a common source of errors.

Fun max (a: Int, B: Int): Int {return if (a> B) a else B // similar to the Java three-object operator (a> B )? A: B}

A value-based expression is very interesting. You do not need to return a value in each if-else as in Java, or set a value. The expression itself is a value, without more assignments, it looks more refreshing.

3. More concise when than switch

The switch statement in Java corresponds to the when. Compared with the switch, the when syntax does not require case-break one by one. The when syntax can accept any object as a parameter or without a parameter, at the same time, when is a value expression:

fun getColor(color: Int) = when(color){     1 -> "Red"     2 -> "Green"     3 -> "Blue" }
4. interval and Series

In Kotlin, there is no general Java for loop, but the interval concept is used to replace this most common loop usage. The essence of an interval is the interval between two values. These two values are usually numbers, a starting value, and an ending value. The... operator is used to represent the interval:

val oneToTen = 1..10

Value of the iteration interval:

for(i in 1..10){    println(i)}

If you can iterate all values in a range, such a range is called a series

Create a descending sequence with a step of 2:

for(i in 100 downTo 1 step 2){      }

Create a semi-closed interval:

For (x in 0 until 100) {}// equivalent to for (x in 0 .. 99 ){}
5. Named parameters and default parameter values

Naming parameters:

When calling a function defined by Kotlin, some parameter names can be explicitly indicated. If the name of a parameter is specified when a function is called, all subsequent parameters need to indicate the name to avoid confusion.

The default parameter value is to specify a default value for the parameter when declaring the function. This avoids the creation of overloaded functions. Here is an example of creating a simple dialog box. to close the dialog box by clicking an area outside the dialog box and using Java, write a function with a Boolean parameter canceledOnTouchOutside, then, reload the function. If you can close the dialog box, assign a value of true. In this way, an additional reload function is added. With the default value of Kotlin, you only need to set the default value to true:

/*** A dialog box with no title and only the prompt and OK buttons is displayed, click edge to disappear * @ param context * @ param question * @ param onOk * @ param canceledOnTouchOutside. By default, the dialog box is displayed and disappears. */fun createSimpleDialog (context: Context, question: String, onOk: dialogInterface. onClickListener ?, CanceledOnTouchOutside: Boolean = true): AlertDialog {val dialog = AlertDialog. builder (context, android. r. style. theme_Material_Light_Dialog_Alert ). setMessage (question ). setPositiveButton (context. getString (R. string. OK), onOk ). create () dialog. setCanceledOnTouchOutside (canceledOnTouchOutside) return dialog}

Call:

CreateSimpleDialog (activity, "Lambda implementation", DialogInterface. OnClickListener {dialog, which->}). show ()

CanceledOnTouchOutside is omitted during the call. The function uses the default value after compilation.

When using the regular call syntax, you must specify parameters in the order defined in the function declaration. You can omit only the parameters at the end. If you use a named parameter, You can omit some intermediate parameters, or you can just specify the parameters you need in any order you want.

6. Top-level functions and attributes

The static method used to replace Java is the top-level function. The top-level function does not belong to any class and is still a member of the package. It can be accessed from outside the package through import. The definition of the top-level attribute is the same as that of the top-level function. Put it in the top-level file.

7. Extended Functions

An extension function is a member function of a class, but it is defined outside the class and called according to the normal method. As shown in the code, String is the class to be extended, which is called the receiver type, the object used to call this extended function is called the receiver object. The receiver object member can also access this without using this:

Package stringsfun String. lastChar (): Char = this. get (this. length-1) // call println ("Kotlin". lastChar ())

It is so simple that a lastChar () method is added to the String class.
To use extended functions, you must import them like other classes or methods.

import strings.lastCharval c = "Kotlin".lastChar()

Essentially, a static function is used to extend a function. It uses the called object as its first parameter. Calling an extension function does not create an adaptation object or any additional consumption during running. This makes it very easy to call the extension function of Kotlin from Java.

Assume that lastChar is declared in a file named StringUtil. kt:

char c = StringUtilKt.lastChar("Java")

Finally, it is worth noting that extended functions do not support rewriting.
Extended functions make it possible to add the class function without changing the original code. Calling an extended function is just like calling a class function.

8. Local functions and extensions

A local function can be understood as a function defined in a function. Using a local function can reduce a lot of repeated code:
Before using a local function:

Class User (val id: Int, val name: String, val address: String) fun saveUser (user: User) {if (user. name. isEmpty () {throw IllegalArgumentException ("Can't save user $ {user. id}: empty Name ")} if (user. address. isEmpty () {throw IllegalArgumentException ("Can't save user $ {user. id}: empty Address ")} // Save the user to the database}

Use local functions:

Fun saveUser (user: User) {fun validate (user: User, value: String, fieldName: String) {if (value. isEmpty () {throw IllegalArgumentException ("Can't save user $ {user. id}: empty $ fieldName ")} validate (user, user. name, "Name") validate (user, user. address, "Address") // Save the user to the database}

After extracting the verification code as a local function, it looks much better. However, it can be optimized to extract the verification logic to the extended functions:

Class User (val id: Int, val name: String, val address: String) fun User. validateBeforSave () {fun User. validate (value: String, fieldName: String) {if (value. isEmpty () {throw IllegalArgumentException ("Can't save user $ id: empty $ fieldName")} validate (name, "Name") validate (address, "Address")} fun saveUser (user: User) {user. validateBeforSave () // Save the user to the database}

In this way, the verification function does not need to be written in the User class at all. If you can observe that the class API can only contain the necessary methods, you can keep the class refined at the same time, it also makes your thinking clearer.

9. Secure call operator :"?. "

Finally, the secure call operator, which is not one of the most popular ones, is :?., A series of null judgments are no longer required for method and attribute calls. Assume that such a class User has an address attribute, which belongs to the Address class and has a cityName attribute. Now there is a reference to the User class and you need to access cityName. the Java code is as follows:

if(user != null && user.addrss != null){    println(user.address.cityName)}

The Kotlin code looks much more comfortable:

println(user?.address?.cityName ?: "")
10. Elvis operator (null merge operator ):"? :"

The Elvis operator receives two operation numbers. If the first operation number is not null, the operation result is the first operation number. Otherwise, the second operation number is:

fun foo(s: String?){    val t: String = s ?: ""}

Elvis operators are often used together with secure call operations. A value is used to replace null returned when a method is called on a null object:

fun strLenSafe(s: String?): Int = s?.length ?: 0

So far, more useful Kotlin syntaxes need to be further discovered!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.