当前位置:网站首页>Getting started with kotlin

Getting started with kotlin

2022-06-11 05:39:00 Zippx.


Preface

from Kotlin Add sample code to the example
install IDEA Of EduTools plug-in unit , And finish Kotlin Practice of the mind seal course
If already There is one Java project , Then you can. :
Begin to Kotlin Add code to the project .
Start with a small class or function , And with Java Annotations required for correct interoperability of the code .
use Kotlin For code Write some tests . The test is to Kotlin Add a safe place to the code base , Because they are not bundled with the application during the packaging process .
take Java Code conversion to Kotlin. extract Java A small fragment of a function , And use Java-to-Kotlin The converter converts it to Kotlin Classes and functions .


Tips : The following is the main body of this article , The following cases can be used for reference

One 、 Create your first Kotlin Applications

Once installed IntelliJ IDEA, You can start creating your first Kotlin The app .
In IntelliJ IDEA, select stay IntelliJ IDEA in , choice File archives | New new | Project The project .
In the panel on the left, select In the left panel , choice Kotlin.
By default , The project will use a kotlindsl Of Gradle Build system .

 Insert picture description here

Two 、 Use steps

1. Click on Finsh establish

Check and accept the default configuration , And then click Finish.

The graph is as follows ( Example ):
 Insert picture description here

2. stay src/main/kotlin Open in main.kt file .

The graph is as follows ( Example ):

 Insert picture description here

3. Run the program .

The graph is as follows ( Example ):

The application is now ready to run . The easiest way is to click on the green in the binding line Run Icon , And then choose Run‘ MainKt’.

 Insert picture description here


3、 ... and 、 Basic grammar

The package declaration is at the top of the source file

package my.demo
import kotlin.text.*

kotlin The entry to the application is main function

fun main(){
    
    println("kotlin")
}

With two int Parameters \ return int function

fun sum(a: Int, b: Int): Int {
    
    return a + b
}

fun main() {
    
    print("sum of 3 and 5 is ")
    println(sum(3, 5))
}

Take the expression as the body of the function , Functions that automatically infer the return value type

fun sum(a: Int, b: Int) = a + b
 
fun main() {
    
    println("sum of 19 and 23 is ${sum(19, 23)}")
}

Function returns a meaningless value

fun printSum(a: Int, b: Int): Unit {
    
    println("sum of $a and $b is ${a + b}")
}
 
fun main() {
    
    printSum(-1, 8)
}

Define read-only local variables using the keyword val Definition , It can only be assigned once

val a: Int = 1  //  Assign immediately 
val b = 2   //  Automatically infer  `Int`  type 
val c: Int  //  If there is no initial value, the type cannot be omitted 
c = 3       //  definitely assigned 

The variable that can be reassigned uses var keyword

var x = 5 //  Automatically infer  `Int`  type 
x += 1

Annotations are like most modern languages ,kotlin Support single line and multi line ( fast ) notes

//  This is a line comment 
 
/*  This is a multi line   Block annotation . */
 also kotlin Comments in can be nested 

/*  Notes start here  /*  Contains nested comments  */     
 And end here . */
 character string 

Grammatical expression

var a = 1
//  Simple name in template :
val s1 = "a is $a" 
a = 2
//  Any expression in the template :
val s2 = "${s1.replace("is", "was")}, but now is $a"
 Conditional expression 
fun maxOf(a: Int, b: Int): Int {
    
    if (a > b) {
    
        return a
    } else {
    
        return b
    }
}

Four 、 Code specification

No matter which language it is, code specifications are indispensable

Directory structure

In pure Kotlin In the project , The recommended directory structure follows a package structure that omits the common root package . for example , If all the code in the project is located in org.example.kotlin In the bag and its subpackages , that org.example.kotlin The package file should be placed directly in the source code root directory , and org.example.kotlin.network.socket The files in should be placed in the root directory of the source code network/socket Subdirectory .

Source file name

If Kotlin The file contains a single class ( And possibly related top-level declarations ), Then the file name should be the same as the name of the class , And add .kt Extension . If the file contains multiple classes or only top-level declarations , Then select a name that describes what the file contains , And name the file accordingly . Hump style with capital letters ( Also known as Pascal style ), for example ProcessDeclarations.kt.

Source file organization

Encourage multiple statements ( class 、 Top level functions or attributes ) Put it in the same Kotlin In the source file , As long as these declarations are semantically closely related to each other and the file size remains reasonable ( Not more than a few hundred lines ).

Especially when defining extension functions for a class that are relevant to all clients of the class , Please put them in the same place as the class itself . When defining extension functions that are only meaningful to the specified customer , Place them next to the customer code . Don't just save “Foo All extension functions of ” And create files .

Class layout

Usually , The contents of a class are listed in the following order :

  • Attribute declaration and initialization block
  • The secondary constructor
  • Method statement
  • Companion

Do not sort method declarations alphabetically or visibly , Don't separate regular methods from extended methods either . It's about putting things together , In this way, people who read from top to bottom can follow up the logic of what happened . Choose a sequence ( High priority , Or vice versa ) And stick to it .

Put nested classes next to the code that uses them . If you plan to use nested classes outside , And these classes are not referenced in the class , Then put them at the end , After companion .

Interface implementation layout

When implementing an interface , The order of implementing members should be the same as that of the interface ( if necessary , Also insert additional private methods for implementation )

Reload layout

Always put overloads together in classes .

summary

Use IntelliJ IDEA Integrated in Kotlin plug-in unit , You can easily start using Kotlin. Highlight... From the code 、 Code completion 、 restructure 、 Debugging and Kotlin Benefit from other available features of .
If you want to Start from scratch , You can create a basic Kotlin Applications . After creating the application , You can learn more about Kotlin grammar Kotlin Use code comparison java More concise Efficient You can also use Kotlin And Java interoperability , And change the increment of the code and the excellent type system to Java, It also provides backward compatible Java Simple migration path for . With more declarations , Less code , Mixed language database , Than Java More expressive , send Kotlin Become the future development direction of enterprise application and mobile

原网站

版权声明
本文为[Zippx.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020537213506.html