Kotlin Learning (2) -- basic syntax, function, variable, string template, conditional expression, null, type detection, for, while, when, interval, set, kotlinnull

Source: Internet
Author: User

Kotlin Learning (2) -- basic syntax, function, variable, string template, conditional expression, null, type detection, for, while, when, interval, set, kotlinnull
1. Basic syntax

Many concepts of Kotlin are similar to those of JAVA, so I should not be as detailed as I did on my JAVA journey, but don't worry, you will understand it, I also learned from official documents.

Create a project Kotlin02 in IDEA

1. Functions (fun)

By default, we have a main function, that is, main.

Fun main (args: Array <String>) {print ("main function ")}

Like JAVA, it is the main entry of the program. Of course, we also have common functions.

Fun sum (): Unit {print ("No parameter no return")} fun sum () {print ("general Unit can be omitted")} fun sum (a: Int) {print ("No parameter returned")} fun sum (): Int {print ("No parameter returned") return 0;} fun sum (a: Int ): int {print ("returns with Parameters") return 0 ;}

Here we can have a clear understanding of the Kotlin function. First, there is a Unit in our no-argument return. This is the flag.
This function has no return value. It is the same as void in JAVA and can be omitted. Note that its value is
Is to define the variable first, and then point to the type with a colon, such as a: Int B: String, and the return value is also pointed to with a colon, such as: Int

In addition, we can also use the expression as the function body and return value type, such:

fun sum(a: Int, b: Int) = a + b;
2. Variable (val & var)

There are three variables: local variables, top-level variables, and variable variables.

But there are two modifiers: val and var.

// Defines the Int type variable val a: Int = 1 // defines the variable to automatically identify the type. If the type is not specified, the value val B = 2 // no initial value must be assigned, not operational val c: Int // value-assigned val modifier can only be assigned once c = 3

After the val modifier is used, only one value can be assigned before the read-only variable is programmed. in JAVA, it can be understood as a constant. How can this problem be solved? It can be said that the final modifier is the same in JAVA, let's give an example.

// Error val a: Int print (a + 2) // correct a = 3 print ()

The meaning here is that I define an Int Type a and then output a + 2. the compiler will prompt an error because there is no value after val modification and cannot be operated, then I assign him a value of 3 to output it correctly.

Another thing to note here is that we can define a variable like val c: Int without assigning a value first, but if you do not specify a value and do not define a type, such as val a, it is wrong, the compiler cannot know what operations you need

Let's take a look at the variable. The usage is the same, but he is variable.

    var a: Int = 2    print(a)    a++;    print("a:" + a)

Here we can understand that input a 2, then a ++, and output 3

There is also the last top-level variable. The top-level variable is actually the global variable in JAVA. There is nothing to say.

// Top-layer val x = 2var y = 3fun sum () {y ++ print (x + y )}

There's nothing to say about it.

3. String template ($)

The string template is also relatively simple, that is, character reference. Let's take a look at an example.

Val boy = 5 var girl = 7 var all = "there are boys in the class: $ boy, girl: $ girl" print (all)

Run and Output

It can be seen that the variables boy and girl are referenced in the output here. You only need to add $ in front of them, which is a bit similar to the escape characters in JAVA.

Of course, there are some more advanced usage, such

Val boy = 5 var girl = 7 var all = "class boys: $ boy, girl: $ girl" // print (all) // Replace the boy with the girl print ("$ {all. replace ("boy", "girl")}, all girls in the current class are: $ {boy + girl }")

Here we can see the output

That is to say, we can operate directly. Of course, such escaping is essentially no different from the following.

Print (all. replace ("boy", "girl") + ", all girls in the current class are:" + (boy + girl ))

What kind of convenience do you think?

4. conditional expression (if else)
// Compare the size of fun maxOf (a: Int, B: Int): Int {if (a> B) {return a} else {return B }}

If else has always been written in this way. Of course, if it is a simple judgment, we can write it like this.

fun maxOf(a: Int, b: Int) = if (a > b) a else b
5. Check for null values and null values (?)

Remember how we write functions in java? For example

Private String testOf (String x) {String y = null; // perform some logical operations if (! TextUtils. isEnty (y) {y = x;} return y ;}

This is a piece of JAVA code. We can see that if we can assign values to y after logical operations, but in the same way, null may be returned, but in kotlin, we need special processing

fun parseInt(str: String): Int? {    return null;}

Note that if the returned value may be null, You need to mark it? Question mark. Otherwise, an error will be reported when you return null.

6. type detection and implicit type conversion (is)

In JAVA, instanceof is used for type detection. In kotlin, is can be used. Let's look at an example.

    var a:Any = "123"    if(a is String){        print(a.length)    }

In this Code, I will explain that Any has a common parent class for all classes, which is similar to an Object. However, it is not as big as an Object.

In this Code, first, I used is to judge the String. Here we can not only judge, but also convert the type. If it is true, we can output. length, but before calling is, there is actually no length method.

7. for Loop (for in)
Var a = listOf (1, 2, 3, 1) for (B in a) {// error // print (B + "\ n ") print ("$ B \ n ")}

In this Code, we define a list as a, and then use in To Go To The for loop. Here I will talk about the application scenario of the string template.

For example, if the output result requires a line break, print (B + "\ n") is incorrect when you use the "+" symbol. print ("$ B \ n") is required "), in Kotlin, in is responsible for the for loop, that is, the maximum number of times is the list length.

Of course, if you want to ask, what should I do if I want to know the subscript?

Var a = listOf (1, 2, 3, 1) for (B in. indices) {print ("item:" + B + "value" + a [B] + "\ n ")}

In fact, in is just a means to provide a loop. To really loop things, you have to decide on your own. So here, I will loop through the subscripts of list a. indices

In this way, I can get the subscript and the corresponding value. Of course, we can write this output in a more official way:

Print ("item: $ B value $ {a [B]} \ n ")

Similarly, we can see the print

8. while loop (while)
    var a = 0;    while (a < 10) {        a++;        print(a)    }

There is nothing to say about the while loop. You just need to follow the normal steps.

9. when expression (when)
Var x = 1; var y = 1; when (x) {1-> if (x + y> 5) {print ("")} else {print ("B")} 2-> print ("x = 2 ") else-> {// note this block print ("x is neither 1 nor 2 ")}}

From this code, you can see something. That's right. In fact, the when expression in Kotlin is the switch statement block in JAVA-> it is equivalent to the case

10. range)
    val x = 5    if (x in 1..10) {        println("fits in range")    }

We can use int to determine whether x is in the range of 1-10. Of course, the interval usage is still quite large, such as series iteration. We will discuss this in detail later.

11. Set

The set has already appeared in the for loop above us.

    var a = listOf(1, 2, 3, 1)    for (b in a) {        print("$b \n")    }

Collections are widely used. We will discuss them later. Here is an example:

/*** There are a bunch of fruits and a bunch of voting members * each of them has 1-3 tickets * and each of them only likes one kind of fruit * If a voter eats this fruit, it will vote for you * If the total score exceeds 5 points * then you will pass the test * We assume five voting staff, 3 fruits * Is he qualified? * /// Release 3 fruit var fruit = listOf ("banana", "apple", "watermelon") // score var fractions = 0; for (fr in fruit) {if (fr is String) {when (fr) {"longan"-> {print ("+ 1 \ n") fractions = fractions + 1 ;} "banana"-> {print ("+ 2 \ n") fractions = fractions + 2;} "orange"-> {print ("+ 2 \ n ") fractions = fractions + 2;} "apple"-> {print ("+ 2 \ n") fractions = fractions + 2 ;} "watermelon"-> {print ("+ 1 \ n") fractions = fractions + 1 ;}}// Calculate if (fractions> 5) {print ("qualified")} else {print ("unqualified ")}

Let's take a look at the output.

This question is a bit rough. You can understand it. It means that we only have three kinds of fruits for three people who like to eat, and they will give me corresponding scores, if the score exceeds 5 points, we can analyze this question.

First, we define a set of fruit to represent my current fruit, and then I define fractions to accumulate scores, start to loop and determine who like to eat, give a few minutes, finally, determine whether the value is greater than 5,

The question is simple, but our logic starts from here.

This is probably a rough introduction of Kotlin. In fact, this beautiful language is more than just the content. When you know this, we can start the next step, at the beginning, there is no detailed explanation of any knowledge point.

If you are interested, you can come to Github to participate.
  • Kotlin
My public account. I look forward to your attention.

View comments

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.