[First line of code--Android] A streamlined version of Kotlin's introductory tutorial

Posted by gazolinia on Sat, 06 Jun 2020 19:57:34 +0200

Google announced Kotlin as the official Android and development language at the I/O conference in 2017, and Android Studio also provides full support for Kotlin. How do I run kotlin's code?adopt https://try.kotlinlang.org Or IDEA and other IDEs that support Kotlin write directly on top of it, and then run away. Here's the main record of how to program through Kotlin

The Foundation of Programming: Variables and Functions


Defining a variable in Kotlin requires declaring two keywords before the variable
	Val (declares an immutable variable = final of java)
	Var (declares variable = java's non-final variable)
	It is recommended that you always use Vals to declare variables and modify them to var declarations if Vals do not meet your needs
 **No symbols need to be added at the end of the line

Code example:

fun main(){
     val a = 10   // Automatic type derivation to Int type
     println("a = "+a)


fun: keyword that defines a function
 Following the fun is the function name
 The name of the function is followed by a pair of parentheses, which declare what parameters the function receives. The number of parameters can be any number of parameters in the form of: (parameter name: parameter type)
Parentheses are followed by an optional return value type, which you can thank directly if you don't need a return value

Code example:

fun largerNum(num1: Int,num2: Int): Int{
	return max(num1, num2) //The max() function is a built-in function in Kotlin that returns the larger of the two parameters
The code above explains that a function is declared with the name largerNum and the parameters num1: Int,num2: Int return value type: Int body is: returns the maximum value of a comparison between num1 and num2

** When there is only one line of code in a function, Kotlin allows us to write the only line of code directly at the end of the function definition, with an equal sign in the middle, without having to write the body of the function.
   The return keyword can also be omitted, or the return value type can be declared without a type inference mechanism.
The above code can be abbreviated as:
fun largerNum(num1: Int,num2: Int) = max(num1, num2) //The max() function is a built-in function in Kotlin that returns the larger of the two parameters

Logical Control of Programs

if condition statement

There are two main conditional statements for Kotlin= if and when
 if is almost identical to java
 ** One more feature than java is that it can have return values, which are the return values of the last line of code in each condition of the if statement
 The if statement refined by using Kotlin's grammar sugar is as follows:
fun largerNum(num1: Int,num2: Int) = if (num1 > num2) num1 else num2

when conditional statement

when is similar to java's switch statement, but more powerful

Code example 1:

fun getScore(name : String) = when (name) {
	"Tom" -> 86
	"Jim" -> 77
	"Jack" -> 95
	"Lily" -> 100
	else -> 0
// Or when usage without parameters
// Kotlin can use==directly instead of calling the equals() method to determine whether strings or objects are equal
fun getScore(name : String) = when  {
	name.startsWith("Tom") -> 99 // All names starting with Tom have a return value of 99
	name == "Tom" -> 86
	name == "Jim" -> 77
	name == "Jack" -> 95
	name == "Lily" -> 100
	else -> 0

Code example 2:

fun checkNum(num : Number) {
		// is equivalent to instanceof in java for type matching
		is Int -> println("number is Int")
		is Double -> println("number is Double")
		else -> println("number not support")

Loop statement

Kotlin's loop statements are mainly for-in loops, while loops (like java).

for-in loop example:

fun main(){
	// The loop traverses a 0-10 closed interval, containing 0 and 10
	for(i in 0..10){
	// Loop traverses 0-10 left closed right open intervals, containing 0 but not 10
	for(i in 0 until 10){
	// The loop traverses the 0-10 left closed right open interval, containing 0 without 10, stepped by 2
	for(i in 0 until 10 step 2){
	// The loop traverses the 10-1 left closed right open interval, containing 10 without 1, stepped by 2
	for(i in 10 downTo until 1 step 2){


Like java, Kotlin is object-oriented

Classes and Objects

Create an object code example:

class Person {
	var name = ""
	var age = 0
	fun eat(){
		println("name is "+name+", age is "+age+" years old.")

// Instantiate the object, call
val p = Person()
p.name = "Jack"
p.age = 18

Inheritance and Constructors

Code example:

// Kotlin creates classes by default that cannot be inherited and needs to add the [open] keyword to allow Person to be inherited
open class Person{
	var name = ""
	var age = 0
	fun eat(){
		println("name is "+name+", age is "+age+" years old.")
// Define the student class, inherit the human object
class Student : Person() {
	var sno = ""
	var grade = 0
Constructors in Kotlin are divided into primary and secondary constructors

Example of main constructor:

// Declare a primary constructor with two parameters
class Student(val sno : String, val grade : Int) : Person(){
	// The body of the primary constructor, using the init structure, in which the logic of the primary constructor is written
		println("sno is "+ sno)
		println("grade is "+ grade)
// Two parameters must be passed in when instantiating
val student = Student("a123",100)

Examples of sub-constructors:

// Add two parameters to the main constructor of the Person class, and leave the others unchanged
open class Person(name: String, age: Int){ ...... }

// Any class can have only one primary constructor, but it can have multiple constructors
// When a class has both primary and secondary constructors, all secondary constructors call the primary constructor
class Student(val sno: String, val grade: Int, name: String, age: Int): Person(name, age){
	// The secondary constructor is defined by the constructor, where the primary constructor is called directly
	constructor(name: String, age: Int) : this("", 0, name, age){}
	// It is still legal to call the secondary constructor above and the primary constructor indirectly.
	constructor(): this("", 0)

// When instantiating Student, you can
 val s1 = Student("a123",100,"Tom",18)
 val s2 = Student("Tom",18)
 val s3 = Student()
// If there is no primary constructor, the secondary constructor calls the parent's constructor
class Student : Person {
	constructor(name: String, age: Int) : super(name, age){}


Both the implementation of the interface in Kotlin and the inheritance of the parent class are implemented using:
Kotlin uses the override keyword to override parent classes or implement functions in interfaces

Code example:

	// Define a learning interface
	interface Study{
		fun readBooks()
		fun doHomework()
// Let the student class implement two parameters received by Student in the construction of learning interface Person
class Student (name: String,age: Int) : Person(name,age), Study {
	override fun readBooks() {
		println(name + " is reading ")
	override fun doHomework() {
		println(name + " is do Homework")
// After the Student example
fun main(){
	val student = Student("Jack", 19)
	// Polymorphic implementation: The following method requires study, but here comes student, because student already implements the study interface
fun doStudy(study: Study){

visibility modifiers

java versus kotlin tables | Modifier | Java | Kotlin | | ------------ | ------------ | ------------ | | public | All classes visible | All classes visible (default)| | private | current class visible | current class visible | | protected | Current class, subclass, class visible under the same package path | Current class, subclass visible | | default | Classes visible under the same package path (default) | None | | internal | None | Classes in the same module are visible |

Data Class

Data Class= M in MVC MVP MVVM is the data type used to map server/database data into memory, providing support for data model for programming logic
 Data classes usually override the equals(), toString(), hashCode() methods

Code example:

// Declaring a data class in Kotlin automatically generates the equals, hashCode, toString methods based on the parameters in the main constructor
data class Cellphone(val brand : String, val price : Double)

Singleton Class

// Define a singleton class, replace class with object
object Singleton{
	fun singletonTest() {
		println("singletonTest is called")

// Call Singleton Class

Lambda expression

Collection creation and traversal

Code example:

val list = listOf("a","b","c","e") // listOf creates an immutable collection with elements that can only be queried and cannot be modified
val list = mutableListOf("a","b","c","e") // mutableListOf creates mutable collections that can be queried and modified
// Set is created almost the same way as list, but set is an unreplicated, disordered set
val set = setOf("A","B","C")
val set = mutableSetOf("A","B","C")
// Creation and assignment of map sets
val map = HashMap<String,Int>()
	map["a"] = 1
	map["b"] = 2
	map["c"] = 3
// You can also use the mapOf and mutableMapOf() functions
val map = mapOf("a" to 1, "b" to 2, "c" to 3)

Functional API

val list = listOf("a","bbb","cc","eeeee")
// A lambda expression can be passed in as a parameter
val maxLength = list.maxBy({ s : String ->  it.length })

// Kotlin specifies that Lambda forms can be moved outside function brackets when the last parameter of a Lambda parameter number function is the last parameter
val maxLength = list.maxBy() { s: String -> s.length }

// If the lambda parameter is the only parameter of a function, the parentheses of the function can be omitted
val maxLength = list.maxBy { s: String -> s.length }

// Based on kotlin's derivation mechanism, it is not necessary to declare the parameter types of lambda expressions
val maxLength = list.maxBy { s -> s.length }

// When the parameter list of a Lambda expression has only one parameter, you can use it keyword instead of declaring the parameter name
val maxLength = list.maxBy { it.length }  // Get the longest element in the list by lambda expression
println("maxLength is "+ maxLength)
A map function in a set that maps each element in the set to a different value, a mapping rule is specified in the lambda expression, and a new set is generated

Code example:

fun main(){
	val list = listOf("a","b","c")
	// Convert each element in the list to uppercase
	var newlist =list.map { it.toUpperCase () }
	for(i in newlist) {
The filter function is used to filter data in a collection

Code example:

fun main(){
	val list = listOf("a","b","c","ssssssssssss")
	// Now filter out the elements in the list that are less than 5 in length, and then uppercase each element
	var newlist =list.filter{ it.length <=5 }.map { it.toUpperCase () }
	for(i in newlist) {
any function is used to determine if at least one element in a set satisfies a specified condition
 The all function is used to determine if all elements in a set satisfy a specified condition

Code example:

fun main(){
	val list = listOf("a","b","c","ssssssssssss")
	var anyRes = list.any{it.length <= 5} // true determines if there is at least one element less than 5 in the list collection
	var allRes = list.all{it.length <= 5}  //  false determines if all elements in a list collection are less than 5 in length

Use of Java Functional API s

Illustrated by calling thread creation in java
 Functional API s can be used if a Java method is called in Kotlin code and the method receives a Java single abstract method interface parameter

Code example:

Thread(Runnable {
	println(" Thread is Running")
// If more than one java single abstract method interface parameter does not exist in the parameter list of a java method, the interface name can be omitted
	println(" Thread is Running")
// When the last parameter of a Lambda function method is taken outside the method, and is the only parameter of the method, parentheses of the method can be omitted
	println(" Thread is Running")

Null Pointer Check

Kotlin defaults to non-nullable parameters and variables, reversing the check for null pointer exceptions ahead of compilation time
fun main(){
// If you need to declare nullable parameters:
// Question mark following Study, declaring that the parameter can be empty
fun doStydy(study: Study?){
	// ?. Indicates that the null assistant invokes the method normally when the object is not null, otherwise it does nothing.
// Combining?.and?: means that text is called if it is not emptyText.length, if text?.length returns null, let it return 0
fun getTextLength(text: String?) = text?.length ?: 0

// !! The non-empty assertion tool means to tell kotlin that it is certain that the content will not be null and that compile-time checks are not necessary. If null occurs during run time, simply throw the npe exception
fun printUpperCase(){
	val upperCase = content!!.toUpperCase()

// let function, which provides a programming interface for a functional api and passes the original calling object as an argument to the lambda expression
fun doStudy(study: Study?){
	// The let function passes the study object itself as an argument to the lambda expression. Can you continue with the simplification below?
	study?.let { stu ->

Little Magic in Kotlin

String Embedded Expression

// Kotlin allows expressions with the syntax structure ${} to be embedded in strings, replacing this part with the result of expression execution at run time
println("hello , ${obj.name} , nice to meet you")

// Braces can be omitted if the expression is a variable
println("hello , $name , nice to meet you")

// When printing variables
val a = "aaa"
val b = "ccc"
println("a = $a , b = $b")

Default values for parameters of functions

// Declares that the default value of the str parameter is hello
fun printParams(num: Int, str: String = "hello"){  Print num,str  }
// If called, only the first parameter needs to be passed in, and the second parameter can use the default value
// Pass through key-value pairs, matching without concern for order
printParams(str = "nihao", num = 123)

// Implement the sub-constructor by default parameter values
class Student(val sno: String = "", val grade :Int = 0, name: String = "",age : Int = 0):Person(name,age){}

Topics: Programming Java Lambda less