preface

  • Kotlin is officially recognized by Google as a level 1 programming language for Android development
  • Today, I will present a comprehensive and detailed introduction to Kotlin, including defining features, configuring usage, and getting started syntax. I hope you will enjoy it.


directory


Definition 1.

  • Level 1 Programming language developed for Android (Google official certification)
  • Launched in 2010 by JetBrains & open source, interworking with the Java language & with a number of new features not yet supported by Java
  • Versions of Android Studio3.0 and later support Kotlin

Characteristics of 2.


3. Configure and use

Here’s how to configure Kotlin for use in Android Studio.

3.1 Android Studio3.0 pre-release

It consists of three steps to complete the Kotlin configuration.

Step 1: Install the Kotlin plug-in

Click on Android Studio Preference -> Plugins -> to search for the Kotlin Languages plugin

Step 2: Add it to build.gradle in the root directory

Buildscript {ext.kotlin_version = '1.2.10' repositories {mavenCentral()} dependencies {classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } }Copy the code

Step 3: Import in app/build.gradle

apply plugin: 'com.android.application' apply plugin: 'kotlin-android' buildScript {ext.kotlin_version = '1.2.10' dependencies {classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } }Copy the code

3.2 Android Studio3.0 version before and after

Android Studio Preference -> Plugins -> Search for Kotlin Languages


4. Basic grammar

In this section, we will explain Kotlin’s basic syntax in detail, including:

  • Basic concepts (vs. Java)
  • The data type
  • class
  • Variables & constants
  • function
  • Other syntactic sugar (control flow, type checking & conversion, security, etc.)

4.1 Basic Concepts

There are some concepts in Kotlin that are quite different from Java, and some basic concepts to be aware of:

  • Operation objects: In Kotlin, all variable member methods and attributes are objects. If no value is returned, the Unit object is returned. Uint can be omitted in most cases; There is no new keyword in Kotlin

  • Datatypes & Conversions: Conversions between base datatypes and wrapper types in Java by boxing and unboxing; In Kotlin, however, both constants and variables must have type annotations or initializations when they are declared, and their data types are derived when they are declared and initialized.

  • Compilation perspective: Like Java, Kotlin is based on the JVM. The difference is that the latter is statically typed, meaning that all variable and expression types are determined at compile time.

  • Writing: In Kotlin, a line of code does not end with a semicolon (;). ; In Java, the semicolon “; “is used. Marks the end of a line of code.

4.2 Data Types

Mainly include:

  • Numbers
  • Characters
  • Strings
  • Boolean (Boolean)
  • Arrays
A. Numbers

Kotlin has six basic numeric types: Byte, Short, Int, Long, Float, and Double

Note: Unlike Java, a character (char) in Kotlin is not a numeric type; it is a separate data type.

  • Note: Each data type can be converted to another data type using the corresponding method
ToByte () : Byte toShort() : Short toInt() : Int toLong() : Long toFloat() : Float toDouble() : Double toChar() : CharCopy the code
B. Characters

The character types in Kotlin are represented by Char and must be enclosed by single quotes using & and cannot be manipulated directly with numbers

val ch :Char = 1; Val ch :Char = '1'; Val ch :Char = '8'; val a :Int = ch.toInt()Copy the code
C. Strings
  • Description: String
  • Features: immutable
  • Use: characters in strings accessed by index: s [I]
// Use 1: a string can be iterated with a for loop for (c in STR) {println(c)} // Use 2: a string can be concatenated with three quotes """ "fun main(args: Array<String>) {val text = """ String 1 String 2 """ println(text) // There are some prespaces} // note: Through trimMargin () to delete redundant blank fun strSample () {val text = "" |" "str1 | str2 | | multi-line string BBBBBB" "" trimMargin println () / / (text) Removed leading space}Copy the code

String Templates

  • That’s a little bit of code inside the string that evaluates and merges the results into the string.
  • Template expressions begin with a dollar character ($)
${varname.fun ()} : ${varname.fun ()} : ${varname.fun ()} : Val s = "ABC" val STR = "$s.length is ${s.length}" // identify "abc.length is 3"Copy the code
D. Boolean type (Boolean)
  • Kotlin’s Boolean is similar to the Java Boolean type, with only true and false values
  • Boolean Built-in function logic operations include:
| | - short circuit logic or && - short circuit logic and! Non - logicCopy the code
E. Array types
  • Implementation: Use the Array class
  • Use the size attribute, get, and set methods. Note: Using [] overrides the get and set methods to get/set array values by subscript.
  • ArrayOf (); arrayOf(); Mode 2 = factory function
[1,2,3] val a = arrayOf(1, 2,3) Create an Array [0,2,4] val b = Array(3, {I -> (I * 2)}) Public inline constructor(size: Int, init: (Int) -> T) println(a[0]) println(b[1]) In addition to the Array class, ByteArray, ShortArray, and IntArray are used to represent various types of arrays. IntArray = intArrayOf(1, 2, 3)Copy the code

Note: Unlike Java, arrays in Kotlin are invariant, i.e. Kotlin does not allow arrays to be assigned to arrays to prevent possible runtime failures

4.3 class USES

A. Class declaration & instantiation

// format class Class name (parameter 1: parameter type, parameter 2: parameter type...) {} // Example class User(userName: String, age: Int){} // Kotlin supports default arguments, that is, when a function is called without specifying an argument, the default function class User(userName: String = "hjc", age: UserName = HJC, age = 26 var user = user (); Var user = user ("ABC", 123) // Name the parameters: Class User(userName: String = "HJC ", age: Int) var user = user (age = 26) var user = user (age = 26)Copy the code

For constructors, a class in Kotlin can have one primary constructor & multiple sub-constructors, as described below.

B. Primary constructor

  • Part of the class header = follows the class name with the constructor keyword
  • Cannot contain any code. The initialized code is placed in a code block prefixed with the init keyword
Constructor () {init {//... Constructor (userName: String) {//... }}Copy the code

Note: Omit the constructor keyword if the main constructor does not have any annotation/visibility modifiers

// Form class class name (parameter name: parameter type) {init {//... } // Example class User (userName: String) {init {//... }}Copy the code

C. Secondary constructor

  • The constructor keyword must be added
  • There can be more than one subconstructor in a class, passing in different arguments
Constructor (constructor) :{// example class User(userName: Constructor () {// init {println(userName)} constructor(); This (" HJC ") // Call the main constructor from this(age: Int) : This (" HJC ") {println(age)} constructor(sex: String, age: Int) : This (" HJC ") {println("$sex$age")}} this(" HJC ") {println("$sex$age")}} this(" HJC ") {println(" HJC ")} User("male",26) // call constructor 3Copy the code

D. Class attributes

Kotlin classes can have attributes: keyword var (read and write)/keyword val (read only)

class User { var userName: String val sex: String = "male"} // Use the property = name + reference User().sex // Use the property = Java getter User().username = "HJC" // Set the property = Java setter methodCopy the code

E. Visibility modifier

  • Private: Visible inside this class
  • Protected: Visible inside & subclasses of this class
  • Public: any client that can see the class declaration (public member)
  • Internal: the class declaration is visible to any client in this module (public member)

Unlike Java, Kotlin’s visible modifier is less default and more internal: the member is visible only within the same module. (Note: a module = a set of Kotlin files compiled together: an IntelliJ IDEA module; A Maven project; A Gradle source set; A < kotlinc > Ant task executes a compiled set of files.

F. Inheritance & override

  • Like Java, Kotlin is single inheritance = there is only one parent class
  • Difference: Kotlin uses the colon “:” for inheritance & inheritance is not allowed by default (to make a class inheritable, use the open keyword)
Open class Fruits class Fruits: Food()Copy the code
  • In Kotlin, methods are also not overridden by default when subclasses override their parent
  • If a subclass wants to override a method in its parent class, it must add the open keyword in front of the method and the Override keyword in front of the method overridden by the subclass
Open class Food {open fun banana() {}} // Subclass class Fruits: Food(){override fun banana() {super.banana()}}Copy the code

Special Class description

Here are some special classes:

  • Nested classes (inner classes)
  • interface
  • Data classes
  • Enumeration class
/** * 1. Nested class (inner class) * flag: keyword inner * use: call nested class */ class User {var age: Int = 0 inner class UserName { } } var userName: User.UserName = User().UserName() /** * 2. Interface A{} interface B{} interface A{} interface B{} Java does not support methods in interfaces that have method bodies. Interface UserImpl{fun getName(): String // No default method body, must override fun getAge(): Int{// have a default method body, can not override the return 22}} // implement the interface UserImpl: GetAge () class User :UserImpl{override fun getName(): String {return "HJC"}} Class Food: A, B {} // Kotlin is more realizing class Fruits: Food,A, B {} /** * 3. // use: when creating a class, the following methods are automatically created: // 1. getter/setter methods; // 2. Equals ()/hashCode(); // 3. toString() : outputs "class name (parameter + parameter value)"; // 4. Copy () function: Copy an object & change some of its properties, but leave the rest unchanged // Example: // Declare 1 data class User(var userName: String, var age: String) Var user = user (" HJC ",26) var user1 = user.copy(age = 30) user1.tostring () User(userName= HJC,age=30) The primary constructor must have at least one argument, which must be marked either val or var // 2. Data classes cannot be open, sealed, sealed, inner /** * 4. Enum class Color {RED, GREEN, BLUE} enum class Color(RGB: RGB) Int) { RED(0xFF0000), GREEN(0x00FF00), BLUE(0x0000FF) }Copy the code

4.4 Variables & Constants

// variable // template: var Variable name: data type = assigned value // rule: // 1. Use "var" to identify the variable. // 2. Data type at the end // 3. Variable names are separated from data types by colons (:) // Example: var a: Int = 1 var a: Int a = 2 // constant // template: val Constant name: data type = specific assigned value // rule: // 1. // 2. The constant name follows val; Data type at the end // 3. Constant names are separated from data types by a colon ":" // Example: val a: Int // Declare an uninitialized variable, the type a = 2 must be explicitly specified // Constant values cannot be changed again val b: Int = 1 // declare and display the specified value // Special note: 1. 1. Automatic type conversion // When defining a variable or constant, if the value is assigned directly without specifying the data type, then the type conversion can be performed automatically. Var a = "aaa" val b = 1 var b = "aaa" val b = 1 var a = "aaa" val b = 1 var a = "aaa" val b = 1 var a = "aaa" val b = 1 Check the data type: operator is n is Int // Check whether n is an integer typeCopy the code

4.5 the function

A. Define & invoke

Function name (parameter name: parameter type) : return value type {function body return return value} // Description: // 1. Use "fun" to identify // 2. Parentheses are the parameter values and types of the passed function // Example: A function named "ABC", the type of the passed parameter is Int, and the type of the returned value is String fun ABC (Int: Int): String {return "carson_ho"} String {return "carson_ho"} String {return "carson_ho"} Fun add(a: Int, b: Int) = a + b; fun add(a: Int, b: Int) = a + b; fun add(a: Int, b: Int) = a + b; // Call a function: suppose a class has a function called foo: User().foo()Copy the code

B. Default parameters

Fun foo(STR: String, int: Int = 1) {println("$STR $I ")} foo(" ABC "); Fun foo(int: int = 1, STR: int) fun foo(int: int = 1, STR: String) {println("$STR $I ")} // Call foo(STR = "hello") // Use the name of the argument to specify the value // Result: hello 1 foo("hello") // Compile error occurredCopy the code

C. Pay special attention

A function, in addition to passing in arguments & returns values, will exist:

  • Passed arguments & no return value
  • No passed arguments & no return value
Void void void void void void void void void void void void void void void Unit{function body} // No argument &no return value // template: fun () {function body} // or return Unit (void, similar to Java) fun () : Unit{function body}Copy the code

4.6 Other grammatical sugars

Some useful grammar candy about Kotlin, mainly including:

  • Control flow (if, when, for, while)
  • Range use (in, downTo, step, until)
  • Type checking & Conversions (IS, Intelligent Conversions, AS)
  • Equals (), =, ==
  • Air safety

A. Control flow statements

Control flow statements include: if, when, for, and while.

If statement
  • The if statement in Kotlin is similar to Java usage
  • The difference is that Kotlin’s if statement is itself an expression with a return value
Var c = if (a > b) 3 else 4 var c = if (a > b) 3 else 4 var c = if (a > b) 3 else 4 3:4; Var c= if (a >b) {code block 1} else {code block 2} // If a>b, execute code block 1, otherwise execute code block 2Copy the code
When statement

Similar to the Switch statement in Java

// Switch statement int a = 0; switch (a) { case 0: break; case 1: break; default: break; Var a = 0 when (a) {0 -> {block 1} 1 -> {block 2} 2,3 -> {block 3} else -> {block 4}} // Execute code block 1 when a=0 // execute code block 2 when a=1 // execute code block 3 when a=2, 3 when a= other values // Note: the when statement terminates execution of the WHEN statement after the conditional branch executionCopy the code
For statement

Similar to the for statement in Java

// For (int I = 0; i < 4; i++) { System.out.println(i); } // Kotlin for if (I in 1.. For (int I = 0; for (int I = 0; for (int I = 0; i < 4; i++) { System.out.println(i); Indices {println(array[I])} for (I in array.indices) {println(array[I])}Copy the code
While statement

Similar to the Java while statement, divided into while and do… While statement:

var i = 5 while(i in 1.. 4){code block 1} do{code block 2}while(I in 1.. 4) {}Copy the code

B. Range use

Indicates the range, including in, downTo, step, and until

/** * 1. [1,5] if (I in 1.. 5) {println(" I within 1-5 ")} He is not in school. If (I! in 1.. 1) {println(" I am not inside 1-5 ")} /** * 2. For (I in 1 until 5) {println(I)} /** * 3. **/ for (I in 1) downTo 1) {println(I)} /** * 4. Step * For (I in 1 downTo 5 step 2) println(I) // Set the step size to 2 and output 5, 3, 1 in reverse order for (I in 1 downTo 5 step 2) println(I)Copy the code

C. Type checking & conversion

/** * 1. Is used to check whether an object is of the specified type **/ If (a is String) {println("a is String ")} if (a! Is Int) {println("a is not an Int ")} /** * 2. Note: Kotlin does not have to use explicit type conversion operations because the compiler tracks is checks for immutable values as well as explicit conversions and automatically inserts (safe) conversions when needed **/ var a: Any = "a" if (a is String) {println("a is String ") println(a.length) A is automatically converted to String if (a! Is String) {print (a. ength)} / / in && and | | right can also be intelligent transformation: / / ` && ` a automatically converted to the String on the right side of the if (a is a String && a. ength > 0) / / ` | | ` a automatically converted to the String on the right side of the if (a is a String | | a. ength > 0) When (a){is String -> a.length is Int -> a + 1} // Note: Smart conversions cannot be used when the compiler cannot guarantee that the variable will not change between checking and using. // 1. Val local variables -- always, except for local delegate attributes; // 2. val attribute -- If the attribute is private or internal, or the check is performed in the same module where the attribute is declared. Smart conversions do not apply to open properties or properties with custom getters; // 3. var local variable -- if the variable is not modified between check and use, is not captured in the lambda that will modify it, and is not a local delegate attribute; // 4. Var attribute -- never possible (because this variable can be changed by other code at any time) /** * 3. Cast: as **/ var any: any = "ABC" var STR: String = any as String Int = 123 var STR: String = String ClassCastException /** * 4. Nullable conversion operator: as? * Nulls cannot be converted to String because the type is not nullable. **/ var STR = null var str2 = STR as String // Throw TypeCastException // Use safe conversion operator as? You can return NULL if the conversion fails, avoiding throwing an exception. var str = null var str2 = str as? String println(str2) // The output is nullCopy the code

[D]. Equality judgment

In Kotlin, there are two kinds of equality judgment: structure equality and reference equality.

/** * 1. Equals () or == * Var a = "1" var b = "1" if (a.equals(b)) {println("a and b are equal "); Var a = 1 var b = 1 if (a == b) {println("a = b ")} /** * 2. Data class User(var name: String, var age: Int var a = User("Czh", 22) var b = User("Czh", If (c == d) {println("a and b are equal ")} else {println(" A and b are not equal ")} If (c === d) {println("a and b references are equal ")} else {println(" A and B references are not equal ")Copy the code

E. air safety

  • NullPointerException is quite common in Java
  • Kotlin has the advantage of avoiding null-pointer exceptions when executing code as much as possible
In Kotlin, there are two situations that are most likely to cause a NullPointerException **/ / case 1: explicitly calling throw NullPointerException() // case 2: using!! Operator // description:!! The operator converts any value to a non-null type and throws an exception if it is null var a = null a!! / / throw KotlinNullPointerException / / case 3: data types cannot be null / / in Kotlin, distinguish between a reference type system can accommodate null (null reference) and does not fit (not null reference) / / such as: // To allow nullability, declare a variable as a nullable String: place a question mark after the String type. For String, it is written: String? var b: String? = "b" b = null /** * 2. .length // means: if b is not null, then b.length is called. .b? .c? .d // If a is not null, the whole expression will return NULL. // If you only perform an operation on non-null values, you can use a? .b? .let { println(it) }Copy the code

That concludes the introductory syntax for Kotlin.


5. To summarize

  • This article provides a comprehensive introduction to Kotlin learning, including defining features, configuring usage, and getting started with syntax
  • In the upcoming articles, I will continue to explain Kotlin, including its usage and syntax. If you are interested, please follow me on my blog: Carson_ho’s Android blog

Please give the top/comment a thumbs up! Because your approval/encouragement is my biggest motivation to write!