On the Basic Grammar of Kotlin Grammar (1)

https://zhuanlan.zhihu.com/p/36079284 

To introduce the basic grammar of Kotlin, first experience the programming style of Kotlin as a whole.

1. The package statement

Defining a package in Kotlin is a bit different from Java. In Kotlin, the directory and package structure do not need to match. Kotlin's source code can be anywhere on the disk.

 

  • 1. The package statement

The source file is usually the same as Java at the beginning of the package declaration.

package com.mikyou.hellokotlin

/**
 * Created by mikyou on 2018/4/1.
 */
fun main(args: Array<String>) {
    println("Hello Kotlin")
}

 

  • 2. The default import of the package
There are multiple packages that are imported into each Kotlin file by default.

Second, the definition of the function

 

  • 1. The function definition uses the keyword "fun", the function parameter format is: "parameter: type", the function return value type "fun(...): Int"
fun sum(a: Int, b: Int, c: Int): Int {
    return a + b + c
}

 

  • 2. The expression is the function body, and the type of the return value can be omitted. You can use Kotlin's type inference function to infer the type of the return value of the function.
fun sum(a: Int, b: Int, c: Int) = a + b + c

 

  • 3. Functions with no return value (similar to void return value in Java)
fun printSum(a: Int, b: Int, c: Int): Unit {
    println(a + b + c)
}

Or omit the Unit type

fun printSum(a: Int, b: Int, c: Int) {
    println("sum = ${a + b + c}")
}

 

  • 4. Variable-length parameter functions can use the "vararg" keyword to identify public void setData(Object... objects) similar to Java.
fun vars(vararg args: Int) {
    for (arg in args) {
        print(arg)
    }
}

 

  • 5. Lambda (anonymous function)
val sumLambda: (Int, Int, Int) -> Int = { a, b, c -> a + b + c }

test

println("sum = ${sumLambda(1, 6, 7)}")

Three, constants and variables

Constants and variables can have no initialization value, but the compiler must be initialized before being referenced. The compiler supports automatic type judgment, that is, the type can not be specified when it is declared, and the compiler judges it. If it is not initialized at the time of declaration, the type of the variable must be provided

 

  • 1. Definition of variable variables: var keyword

var <variable name>: <variable type> = <initial value>

var sum: Int = 3
sum = 8

//由于编译支持类型推导可以省略Int类型
var sum = 3
sum = 8

 

  • 2. The definition of immutable variables: the val keyword, which cannot be assigned twice, similar to the final type in Java

val <constant name>: <constant type> = <initial value>

val sum: Int //没有赋值初始化之前必须指定类型
sum = 5

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

<h3 id = "4">四、注释</h3>

> Kotlin 支持单行和多行注释,和java中类似。


<h3 id = "5">五、字符串模板</h3>

 * 1、模板中的简单名称


```kotlin
fun main(args: Array<String>) {
    var a = 1
    var s1 = "a is $a"
}

 

  • 2. Any expression in the template
fun main(args: Array<String>) {
    var a = 1
    a = 2
    val s2 = "${s1.replace("is", "was")}, but now is $a"
}

Six, use conditional expressions

 

  • Use if expression to replace the ternary operator in java
fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

fun main(args: Array<String>) {
    println(maxOf(1, 5))
}

The if expression in Kotlin has a return value, so it can be simplified into the following form.

fun maxOf(a: Int, b: Int) = if (a > b) a else b

fun main(args: Array<String>) {
    println(maxOf(1, 5))
}

Seven, NULL check mechanism

Kotlin air safety design parameters for the statement may be empty, when in use to be empty judging process, there are two approaches, the field plus !! like Java throw an empty exception , another field after adding? Can not do Processing return value is null or cooperate?: short judgment processing
//类型后面加?表示可为空
var age: String? = "23"
//字段后面加"!!"抛出空指针异常
val ages = age!!.toInt()
//字段后面加”?“不做处理返回 null
val ages1 = age?.toInt()
//使用”?:“ 表示age为空返回-1
val ages2 = age?.toInt() ?: -1

 

  • 1. When a reference may have a null value, the corresponding type declaration must be clearly marked as "?" after the type to indicate that it can be null.
    When the string content in str is not an integer, return null:
fun main(args: Array<String>) {
    if (args.size < 2) {
        println("Two Integers Expected")
        return
    }
    val x = parseInt(args[0])
    val y = parseInt(args[1])

    //println(x + y) 由于标识了可能为null,直接使用x + y在编译器看来是非法,需要去做非空判断
    if (x != null && y != null) {
        println(x + y)
    }
}

fun parseInt(s: String): Int? {//表示当前函数返回值可能为null,就必须在类型后面标识"?"
    return s.toInt()
}

Eight, type detection and automatic type conversion

We can use the is operator to check whether an expression is an instance of a certain type (similar to the instanceof keyword in Java).

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // 做过类型判断以后,obj会被系统自动转换为String类型
        return obj.length
    }

    //在这里还有一种方法,与Java中instanceof不同,使用!is
    // if (obj !is String){
    //   // XXX
    // }

    // 这里的obj仍然是Any类型的引用
    return null
}

or

fun getStringLength(obj: Any): Int? {
  if (obj !is String)
    return null
  // 在这个分支中, `obj` 的类型会被自动转换为 `String`
  return obj.length
}

It can even be like this

fun getStringLength(obj: Any): Int? {
  // 在 `&&` 运算符的右侧, `obj` 的类型会被自动转换为 `String`
  if (obj is String && obj.length > 0)
    return obj.length
  return null
}

Nine, interval

Use the in operator to detect whether a number is within a specified range. The range expression has the operator form ".." rangeTo function to assist in and !in combination. The interval can support any type that can be compared. For the native integer type, there is an internal optimized implementation.

 

  • 1. Detect whether a number is within a specified interval
val x = 10
val y = 9
if (x in 1..y + 1) {//表示x是否在1~y+1范围内。
    println("fits in range")
}

 

  • 2. Detect whether a number is outside the specified interval
val list = listOf("a", "b", "c")
if (-1 !in 0..list.lastIndex) {
    println("-1 is out of range")
}

if (list.size !in list.indices) {
    println("list size is out of valid list indices range too")
}

 

  • 3. Interval iteration
for(x in 1..10){//相当于 x >= 1 && x <= 10
    println(x)
}

or

fun printList(num: Int) {
    for (i in 1..num) {//相当于 i >= 1 && i <= num
        print(i)
    }
}

Use until function to exclude ending elements

for (i in 1 until 10) {// i in [1, 10) 排除了 10,相当于 i >= 1 && i < 10
    println(i)
}

 

  • 4. Sequence iteration
for(x in 1..100 step 2){//递增数列迭代,每次间隔步长是2;1,3,5,7...
    println(x)
}

for(x in 9 downTo 0 step 3){//递减数列迭代,每次间隔步长是3;9,6,3,0
    println(x)
}

10. Use collections

 

  • 1. Iterate over the collection
fun main(args: Array<String>) {
    val items = list.of("java", "kotlin", "python")
    for (item in items) {
        println(item)
    }
}

 

  • 2. Use the in operator to determine whether a set contains an instance
when {
    "java" in items -> println("is good lang")
    "kotlin" in items -> println("is good good lang")
    else -> println("python is best lang")
}

 

  • 3. Use lambda expressions to filter and map collections
fun main(args: Array<String>) {
    val langs = listOf("C", "C++", "Java", "Python", "JavaScript")

    langs.filter { it.startsWith("C") }
            .sortedBy { it }
            .map { it.toUpperCase() }
            .forEach { println(it) }
}

11. Use loop

There are two ways to loop in Kotlin: for, while, use "in" to traverse in the for loop, and there are two traversal methods.

 

  • 1. For loop
val items = listOf("java", "kotlin", "android")
for (item in items) {//for遍历集合
    println("lang $item")
}

for (index in items.indices) {//类似于java中的数组的length-index的遍历
    println("The $index index is ${items[index]}")
}

 

  • 2. The while loop
val items = listOf("java", "kotlin", "android")
var index = 0
while (index < items.size) {//while 循环的遍历方式
    println("The $index lang is ${items[index++]}")
}

Twelve, use conditions if, when

The use of if in kotlin is similar to java, but if in kotin is an expression that has value, and in java is a statement, you can use if expression in kotlin to replace the ternary operator in java in kotlin. when is similar to switch

fun main(args: Array<String>) {
    println(descript("hello"))
}

fun descript(obj: Any): String = when (obj) {
    1 -> "one"
    "hello" -> "hello word"
    is Long -> "long type"
    !is String -> "is not String"
    else -> {
        "unknown type"
    }
}

Thirteen, create classes and instances

fun main(args: Array<String>) {
    val rectangle = Rectangle(100.0, 200.0)
    val triangle = Triangle(100.0, 100.0, 100.0)
    println("rectangle is ${rectangle.isSquare}, and perimeter is ${rectangle.perimeter}, and area is ${rectangle.calculateArea()}")
    println("triangle  perimeter is ${triangle.perimeter}, and area is ${triangle.calculateArea()}")
}

abstract class Shape(val sides: List<Double>) {
    val perimeter: Double get() = sides.sum()
    abstract fun calculateArea(): Double
}

interface RectangleProperity {
    val isSquare: Boolean
}

class Rectangle(var height: Double, var length: Double)
    : Shape(listOf(height, length, height, length)), RectangleProperity {
    override fun calculateArea(): Double = height * length
    override val isSquare: Boolean get() = height == length
}

class Triangle(var sideA: Double, var sideB: Double, var sideC: Double)
    : Shape(listOf(sideA, sideB, sideC)) {
    override fun calculateArea(): Double = sideA * sideB * sideC
}

At this point, the basic grammar of Kotlin entry is over. The next article will continue to dive into Kotlin-related content.

Guess you like

Origin blog.csdn.net/az44yao/article/details/112917634