This is the 7th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
preface
Kotlin has become an essential language for Android development.
In this column, I will take you from the ground up to learn Kotlin, from basic syntax to coroutine mastery, allowing you to completely transfer from Java to the Kotlin army! Stay tuned!
Note: In the Kotlin Basics tutorial, IDEA will be used as the compiler.
This article is only a preliminary grammar, not intended to go into depth. Master the basics first, and then learn Kotlin step by step.
1. HelloWord
Learning a language is full of ritual.
fun main(a) {
var hello="Hello word";
println (hello)
println( hello.javaClass.name)
hello="Hello my word"
println("this is my first kotlin project: $hello")
val age: Int = 10;
//age=12
val size =12
println("age-------> $age")}Copy the code
Let’s look at this code in action first, and then analyze it
Connected to the target VM, address: '127.0.0.1:61364', transport: 'socket'
Hello word
java.lang.String
this is my first kotlin project: Hello my word
age-------> 10
Disconnected from the target VM, address: '127.0.0.1:61364', transport: 'socket'
Copy the code
Here we see:
- There are two ways to define a variable in Kotlin, namely
val
andvar
; - In Kotlin, variables can be defined in the format var/val variable name: variable type = attribute value;
- You can also use var/val variable name = attribute value to confirm the type of the variable.
- through
var
The variable defined can modify the corresponding variable attribute value; - And by
val
A defined variable cannot change its property value (similar to Final in Java); - You don’t have to write semicolons after code statements
;
the - Used when concatenating strings using variables
The special symbol $+ variable name
;
The corresponding variables can be used to concatenate strings. Can simple logic be used to concatenate strings?
2. Conditional statement judgment
2.1 if.. else..
fun main(a) {
val orgin = "Jack"
val dest = "Rose"
println("$orgin love $dest")
val flag = false
/** * ${} syntax can do simple logic in the string */
println("The Answer is:${if (flag) "I can." else "You're a good person."}")}Copy the code
${} syntax is used to concatenate strings. Run to see the effect:
Connected to the target VM, address: '127.0.0.1:65152', transport: 'socket'Disconnected from the target VM, address:'127.0.0.1:65152', transport: 'socket'
Copy the code
When the ${} syntax is used, simple conditional statements can be used inside curly braces.
Here we use if.. else.. Syntax, then Java inside the switch.. Case syntax? What’s it like in Kotlin?
2.2 the when (XXX) {.. }
Example 1:
fun main{
val school="Primary school"
val level:Any=when(school){
"Preschool"->"Children"
"Primary school"->"Children"
"High school"->"Teenagers"
"University"->"Adult"
else ->{
print("Unknown")
}
}
println(level)
}
Copy the code
Let’s take a look at the results:
Connected to the target VM, address: '127.0.0.1:49681', transport: 'socket'Kid Disconnected from the target VM, address:'127.0.0.1:49681', transport: 'socket'
Copy the code
When can be understood as the Java switch; And the corresponding “preschool” can be understood as the corresponding case “preschool”, “children” can be understood as the logical code after the corresponding case; Else can be interpreted as the corresponding default.
Example 2:
fun main{
var age=12
age++
when (age) {
in 0.8. -> {
println("Children, age:$age")}in 8.18. -> {
println("Adolescents, age:$age")}else -> {
println("Adult, age:$age")}}}Copy the code
The code is pretty simple, this time it’s an expression, is it in some interval. Directly look at the operation effect:
Connected to the target VM, address: '127.0.0.1:50707', transport: 'socket'Disconnected from the target VM, address:'127.0.0.1:50707', transport: 'socket'
Copy the code
As you can see from these two small demos, in the WHEN closure you can use simple expressions to access different business logic.
Now that we’ve covered variable definitions and the basics of conditional statement determination, it’s time to turn to methods.
3. Definition and use of methods
3.1 Example 1:
fun main{
var helloStr: String = hello("Tom")
println(helloStr)
/** * When a method is called, if the method has more than one parameter, the */ value can be specified unordered
helloStr = hello(age = 18, name = "bob")
println(helloStr)
add(12.13.5 F)}private fun hello(name: String, age: Int = 12): String {
return "Hi,My Name is $name ,My Age is $age"
}
private fun add(a: Int, b: Float) {
println("a+b= ${a + b} ")}Copy the code
Or still first look at the effect:
Connected to the target VM, address: '127.0.0.1:53401', transport: 'socket'Hi,My Name is Tom,My Age is 12 Hi,My Name is Bob,My Age is 18 A +b='127.0.0.1:53401', transport: 'socket'
Copy the code
You can see from this code:
- The basic syntax for defining methods:
Fun + method name +(various parameters): method return value {}
; - When you define a method, you can assign an initial value to the corresponding parameter. When there is an initial value, you can use it without passing the corresponding parameter parameter.
- When using the corresponding method, the default is to assign parameters in the order they are defined, although assignments can be specified.
3.2 Example 2:
var letter = "Mississippi"
fun main{
var total = "Mississippi".count()
println(total)
val totals = letter.count { letter -> letter == 's' }
println(totals)
}
Copy the code
Running effect
Connected to the target VM, address: '127.0.0.1:54286', transport: 'socket'
11
4
Disconnected from the target VM, address: '127.0.0.1:54286', transport: 'socket'
Copy the code
It can be seen from this operation effect:
.count()
A veritable count- while
.count {}
This means that only the closure contents are countedtrue
The number of times
Knock on the blackboard!! Next important!!
3.3 Example 3:
fun main{
val bb: (age: Int, name: String, sex: Int) -> String = { age: Int, name: String, sex: Int ->
val holiday = "New Year."
var str = "Happy $holiday"
"$str your age= $age; your name=$name; your sex=${if (sex==2) "Male" else "Female"}"
}
println(bb(12."Zhang".2))}Copy the code
For those of you who don’t know Kotlin, you might wonder: Isn’t val used to define variables? How did the following become a method call? What are you doing? What does that mean?
When defining a variable, you can specify var/val: as the corresponding variable type. So we’re going to follow this syntax here
(age: Int, name: String, sex: Int) -> String = { age: Int, name: String, sex: Int ->
val holiday = "New Year."
var str = "Happy $holiday"
"$str your age= $age; your name=$name; your sex=${if (sex==2) "male" else "female "}"
}
Copy the code
(age: Int, name: String, sex: Int) -> String (age: Int, name: String, sex: Int) -> String (age: Int, name: String, sex: Int) -> String
If it is really the definition of a method, what is its method name? Wait!! Is it bb that we just defined? And then the method is the type of the variable bb, right? And then the curly braces are the implementation of the method, okay? Oh!!!!!!
Suddenly, you run the code:
Connected to the target VM, address: '127.0.0.1:57927', transport: 'socket'Happy New Year. your age= 12 ; Your name= zhang SAN; Your sex= male Disconnected from the target VM, address:'127.0.0.1:57927', transport: 'socket'
Copy the code
Took a look at the operation effect, as expected, is really according to the results of their own imagination.
3.4 Example 4:
fun main{
val getDiscountWords: (goodsName: String, hour: Int) -> String = { goodsName: String, hour: Int ->
val currentYear = 2027
"$currentYear11 years, the double${goodsName}Countdown to promotion:${hour}Hours. ""
}
showOnBoard("Restaurant paper", getDiscountWords);
}
fun showOnBoard(goodsName: String, showDisCount: (String.Int) - >String) {
// Select a random number between 1 and 24
val hour: Int = (1.24.).shuffled().last()
println(showDisCount(goodsName, hour))
}
Copy the code
Once again, you can tell at a glance that getDiscountWords is a method, that it returns a String, and that the contents of the closure are the implementation of the method.
Now let’s go to the showOnBoard method. We see that the first parameter is of type String; Println (showDisCount(goodsName, hour)); The getDiscountWords method passed in above is called.
Now look at this in action with this analysis:
Connected to the target VM, address: '127.0.0.1:59158', transport: 'socket'Disconnected from the Target VM, Address:'127.0.0.1:59158', transport: 'socket'
Copy the code
Hahaha, it worked perfectly.
conclusion
At this point, I believe you have a preliminary understanding of Kotlin. In the next post, we’ll take a closer look at Kotlin’s syntax!