当前位置:网站首页>Getting started with kotlin
Getting started with kotlin
2022-06-11 05:39:00 【Zippx.】
List of articles
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 .

Two 、 Use steps
1. Click on Finsh establish
Check and accept the default configuration , And then click Finish.
The graph is as follows ( Example ):
2. stay src/main/kotlin Open in main.kt file .
The graph is as follows ( Example ):

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’.

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
边栏推荐
- 自定义View之基础篇
- 20多种云协作功能,3分钟聊透企业的数据安全经
- NDK learning notes (x) POSIX socket for connectionless communication
- (15) Infrared communication
- BERT知识蒸馏
- AltiumDesigner2020导入3D Body-SOLIDWORKS三维模型
- MySQL circulates multiple values foreach, XML writing method
- Preliminary understanding of multi task learning
- AttributeError: ‘HistGradientBoostingClassifier‘ object has no attribute ‘_ n_ features‘
- Deep search + backtracking
猜你喜欢

NDK learning notes (VI) Basics: memory management, standard file i/o

Wechat applet, automatic line feed for purchasing commodity attributes, fixed number of divs, automatic line feed for excess parts

mysql字符串转数组,合并结果集,转成数组

NFC Development -- utility tools and development documents (IV)

Cocoapods installation error

推荐一款免费的内网穿透开源软件,可以在测试本地开发微信公众号使用

Analyze while doing experiments -ndk article -jni uses registernatives for explicit method registration

Number of atoms (easy to understand)

(十五)红外通信

Getbackgroundaudiomanager controls music playback (dynamic binding of class name)
随机推荐
Section III: structural characteristics of cement concrete pavement
Create cool collectionviewcell conversion animation
How to apply for free idea with official documents
Opencv learning path (2-4) -- Deep parsing cvtcolor function
(15) Infrared communication
Recommend a free intranet penetration open source software that can be used in the local wechat official account under test
Poverty has nothing to do with suffering
How to deal with message blackout and message sending failure of Aurora im
WinForm (II) advanced WinForm and use of complex controls
如何让灯具智能化,单火、零火智能开关怎么选!
If the MAC fails to connect with MySQL, it will start and report an error
getBackgroundAudioManager控制音乐播放(类名的动态绑定)
项目-智慧城市
Multithreading tutorial (XXVI) field updater and atomic accumulator
Opencv learning path (2-5) -- Deep parsing imwrite function
Exploration of kangaroo cloud data stack on spark SQL optimization based on CBO
Deep learning distributed training
[go deep into kotlin] - flow advanced
NDK learning notes (VII) system configuration, users and groups
(十五)红外通信