kotlin从入门到精通之内置类型

基本类型

kotlin从入门到精通之内置类型_第1张图片

声明变量

kotlin从入门到精通之内置类型_第2张图片
val(value的简写)用来声明一个不可变的变量,这种变量在初始赋值之后就再也不能重新赋值,对应Java中的final变量。
var(variable的简写)用来声明一个可变的变量,这种变量在初始赋值之后仍然可以再被重新赋值,对应Java中的非final变量。
kotlin从入门到精通之内置类型_第3张图片

类型自动推导

kotlin还能对我们的声明的变量进行类型的自动推导:
kotlin从入门到精通之内置类型_第4张图片

易混淆的Long类型标记

kotlin从入门到精通之内置类型_第5张图片

Kotlin的数值类型转换

kotlin从入门到精通之内置类型_第6张图片

无符号类型

目的是为了兼容C
kotlin从入门到精通之内置类型_第7张图片

Kotlin的字符串

kotlin从入门到精通之内置类型_第8张图片


fun main() {

    var a = 2
    val b = "Hello Kotlin"

//    val c = 12345678910l // compile error.
    val c = 12345678910L // ok

    val d = 3.0 // Double, 3.0f Float

    val e: Int = 10
    //val f: Long = e // implicitness not allowed
    val f: Long = e.toLong() // implicitness not allowed

    val float1: Float = 1f
    val double1 = 1.0

    val g: UInt = 10u
    val h: ULong = 100000000000000000u

    val i: UByte = 1u

    println("Range of Int: [${Int.MIN_VALUE}, ${Int.MAX_VALUE}]")
    println("Range of UInt: [${UInt.MIN_VALUE}, ${UInt.MAX_VALUE}]")

    val j = "I❤️China"
    println("Value of String 'j' is: $j") // no need brackets
    println("Length of String 'j' is: ${j.length}") // need brackets
    System.out.printf("Length of String 'j' is: %d\n", j.length)

    val k = "Today is a sunny day."
    val m = String("Today is a sunny day.".toCharArray())
    println(k === m) // compare references.
    println(k == m) // compare values.

    val n = """
                
                
                
                    
                    Hello World
                
                
                    

Hello World

This is a demo page.

"""
.trimIndent() println(n) }

public class JavaBasicTypes {
    public static void main(String... args) {

        int a = 2;
        final String b = "Hello Java";

        long c = 12345678910l; // ok but not good.
        long d = 12345678910L; // ok

        int e = 10;
        long f = e; // implicit conversion

        // no unsigned numbers.

        String j = "I❤️China";
        System.out.println("Value of String 'j' is: " + j);
        System.out.println("Length of String 'j' is: " + j.length());
        System.out.printf("Length of String 'j' is: %d\n",  j.length());

        String k = "Today is a sunny day.";
        String m = new String("Today is a sunny day.");
        System.out.println(k == m); // compare references.
        System.out.println(k.equals(m)); // compare values.

        String n = "\n" +
                "\n" +
                "\n" +
                "    \n" +
                "    Hello World\n" +
                "\n" +
                "\n" +
                "    
\n" + "

Hello World

\n"
+ "

This is a demo page.

\n"
+ "
\n"
+ "\n" + ""; System.out.println(n); } }

数组Array

kotlin从入门到精通之内置类型_第9张图片

数组的创建

kotlin从入门到精通之内置类型_第10张图片

数组的长度

kotlin从入门到精通之内置类型_第11张图片

数组的读写

kotlin从入门到精通之内置类型_第12张图片

数组的遍历

kotlin从入门到精通之内置类型_第13张图片
kotlin从入门到精通之内置类型_第14张图片

数组的包含关系

kotlin从入门到精通之内置类型_第15张图片


fun main() {

    val a = IntArray(5)
    println(a.size) //same with the Collections(e.g. List)

    val b = ArrayList<String>()
    println(b.size)

    val c0 = intArrayOf(1, 2, 3, 4, 5)
    val c1 = IntArray(5){ 3 * (it + 1) } // y = 3*(x + 1)

    println(c1.contentToString())

   val d = arrayOf("Hello", "World")
    d[1] = "Kotlin"
    println("${d[0]}, ${d[1]}")

    val e = floatArrayOf(1f, 3f, 5f, 7f)
    for (element in e) {
        println(element)
    }

    e.forEach {
        println(it)
    }

    if(1f in e){
        println("1f exists in variable 'e'")
    }

    if(1.2f !in e){
        println("1.2f not exists in variable 'e'")
    }

}


import java.util.ArrayList;

public class JavaArrays {
    public static void main(String... args) {

        int[] a = new int[5];
        System.out.println(a.length);// only array use 'length'

        ArrayList<String> b = new ArrayList<>();
        System.out.println(b.size());

        int[] c = new int[]{1, 2, 3, 4, 5};

        String[] d = new String[]{"Hello", "World"};
        d[1] = "Java";
        System.out.println(d[0] + ", " + d[1]);

        float[] e = new float[]{1, 3, 5, 7};
        for (float element : e) {
            System.out.println(element);
        }

        for (int i = 0; i < e.length; i++) {
            System.out.println(e[i]);
        }

        // Test in an Array
        for (float element : e) {
            if(element == 1f){
                System.out.println("1f exists in variable 'e'");
                break;
            }
        }

        //Test not in an Array
        boolean exists = false;
        for (float element : e) {
            if(element == 1.2f){
                exists = true;
                break;
            }
        }

        if(!exists){
            System.out.println("1.2f not exists in variable 'e'");
        }

    }
}

区间

区间的创建

闭区间

kotlin从入门到精通之内置类型_第16张图片

开区间

kotlin从入门到精通之内置类型_第17张图片

倒序区间

kotlin从入门到精通之内置类型_第18张图片

区间的步长

kotlin从入门到精通之内置类型_第19张图片

区间的迭代

kotlin从入门到精通之内置类型_第20张图片

区间的包含关系

kotlin从入门到精通之内置类型_第21张图片

区间的应用

kotlin从入门到精通之内置类型_第22张图片

fun main() {

    val intRange = 1..10 // [1, 10]
    val charRange = 'a'..'z'
    val longRange = 1L..100L

    val floatRange = 1f .. 2f // [1, 2]
    val doubleRange = 1.0 .. 2.0

    println(intRange.joinToString())
    println(floatRange.toString())

    val uintRange = 1U..10U
    val ulongRange = 1UL..10UL

    val intRangeWithStep = 1..10 step 2
    val charRangeWithStep = 'a'..'z' step 2
    val longRangeWithStep = 1L..100L step 5

    println(intRangeWithStep.joinToString())

    val intRangeExclusive = 1 until 10 // [1, 10)
    val charRangeExclusive = 'a' until 'z'
    val longRangeExclusive = 1L until 100L

    println(intRangeExclusive.joinToString())

    val intRangeReverse = 10 downTo 1 // [10, 9, ... , 1]
    val charRangeReverse = 'z' downTo 'a'
    val longRangeReverse = 100L downTo 1L

    println(intRangeReverse.joinToString())

    for (element in intRange) {
        println(element)
    }

    intRange.forEach {
        println(it)
    }

    if (3.0 !in doubleRange) {
        println("3 in range 'intRange'")
    }

    if (12 !in intRange) {
        println("12 not in range 'intRange'")
    }

    val array = intArrayOf(1, 3, 5, 7)
    for (i in 0 until array.size) {
        println(array[i])
    }

    for(i in array.indices){
        println(array[i])
    }
}

集合框架

kotlin从入门到精通之内置类型_第23张图片

集合框架的接口类型对比

kotlin从入门到精通之内置类型_第24张图片

集合框架的创建

kotlin从入门到精通之内置类型_第25张图片
kotlin从入门到精通之内置类型_第26张图片
kotlin从入门到精通之内置类型_第27张图片

集合实现类复用与类型别名

kotlin从入门到精通之内置类型_第28张图片

集合框架的读写和修改

kotlin从入门到精通之内置类型_第29张图片
kotlin从入门到精通之内置类型_第30张图片

kotlin从入门到精通之内置类型_第31张图片
kotlin从入门到精通之内置类型_第32张图片
kotlin从入门到精通之内置类型_第33张图片

Pair

kotlin从入门到精通之内置类型_第34张图片
kotlin从入门到精通之内置类型_第35张图片

Triple

kotlin从入门到精通之内置类型_第36张图片

fun main() {

    val intList: List<Int> = listOf(1, 2, 3, 4)
    val intList2: MutableList<Int> = mutableListOf(1, 2, 3, 4)

    val map: Map<String, Any> =
        mapOf("name" to "benny", "age" to 20)
    val map2: Map<String, Any> =
        mutableMapOf("name" to "benny", "age" to 20)

    val stringList = ArrayList<String>()

    for (i in 0 .. 10){
        stringList.add("num: $i")
    }

    for (i in 0 .. 10){
        stringList += "num: $i"
    }

    for (i in 0 .. 10){
        stringList -= "num: $i"
    }

    stringList[5] = "HelloWorld"
    val valueAt5 = stringList[5]

    val hashMap = HashMap<String, Int>()
    hashMap["Hello"] = 10
    println(hashMap["Hello"])

//    val pair = "Hello" to "Kotlin"
//    val pair = Pair("Hello", "Kotlin")
//
//    val first = pair.first
//    val second = pair.second
//    val (x, y) = pair

    val triple = Triple("x", 2, 3.0)
    val first = triple.first
    val second = triple.second
    val third = triple.third
    val (x, y, z) = triple

}
import java.util.*;

public class JavaCollections {
    public static void main(String... args) {

        List<Integer> intList = new ArrayList<>(Arrays.asList(1, 2, 3, 4));


        List<String> stringList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            stringList.add("num: " + i);
        }

        for (int i = 0; i < 10; i++) {
            stringList.remove("num: " + i);
        }

        stringList.set(5, "HelloWorld");
        String valueAt5 = stringList.get(5);

        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Hello", 10);
        System.out.println(hashMap.get("Hello"));
    }
}

函数

有自己的类型,可以赋值、传递,并再合适的条件下调用

函数的定义

kotlin从入门到精通之内置类型_第37张图片
kotlin从入门到精通之内置类型_第38张图片

函数vs方法

kotlin从入门到精通之内置类型_第39张图片

函数的类型

kotlin从入门到精通之内置类型_第40张图片

函数的引用

函数的引用类似C语言的函数指针,可用于函数传递
kotlin从入门到精通之内置类型_第41张图片
kotlin从入门到精通之内置类型_第42张图片
由于类型可以自动推断,所以可以不用写类型名
kotlin从入门到精通之内置类型_第43张图片
kotlin从入门到精通之内置类型_第44张图片
kotlin从入门到精通之内置类型_第45张图片

变长参数

kotlin从入门到精通之内置类型_第46张图片
kotlin从入门到精通之内置类型_第47张图片
kotlin从入门到精通之内置类型_第48张图片
kotlin从入门到精通之内置类型_第49张图片

多返回值

kotlin从入门到精通之内置类型_第50张图片

默认参数

kotlin从入门到精通之内置类型_第51张图片
kotlin从入门到精通之内置类型_第52张图片

具名参数

kotlin从入门到精通之内置类型_第53张图片

package com.bennyhuo.kotlin.builtintypes.functions

fun main(vararg args: String) {
    println(args.contentToString())

    val x:(Foo, String, Long)->Any = Foo::bar
    val x0: Function3<Foo, String, Long, Any> = Foo::bar
    // (Foo, String, Long)->Any = Foo.(String, Long)->Any = Function3

    val y: (Foo, String, Long) -> Any = x
    val z: Function3<Foo, String, Long, Any> = x

    yy(x)

    val f: ()->Unit = ::foo
    val g: (Int) ->String = ::foo
    val h: (Foo, String, Long)->Any
            = Foo::bar

    multiParameters(1, 2, 3, 4)

    defaultParameter(y = "Hello")

    val (a, b, c) = multiReturnValues() //伪
    val r = a + b
    val r1 = a + c

}

fun yy(p: (Foo, String, Long) -> Any){
    //p(Foo(), "Hello", 3L)
}

class Foo {
    fun bar(p0: String, p1: Long): Any{ TODO() }
}

fun foo() { }
fun foo(p0: Int): String { TODO() }

fun defaultParameter(x: Int = 5, y: String, z: Long = 0L){
    TODO()
}

fun multiParameters(vararg ints: Int){
    println(ints.contentToString())
}

fun multiReturnValues(): Triple<Int, Long, Double> {
    return Triple(1, 3L, 4.0)
}


案例:四则计算器

/**
 * input: 3 * 4
 */
fun main(vararg args: String) {
    if(args.size < 3){
        return showHelp()
    }

    val operators = mapOf(
        "+" to ::plus,
        "-" to ::minus,
        "*" to ::times,
        "/" to ::div
    )

    val op = args[1]
    val opFunc = operators[op] ?: return showHelp()

    try {
        println("Input: ${args.joinToString(" ")}")
        println("Output: ${opFunc(args[0].toInt(), args[2].toInt())}")
    } catch (e: Exception) {
        println("Invalid Arguments.")

        showHelp()
    }
}

fun plus(arg0: Int, arg1: Int): Int{
    return arg0 + arg1
}

fun minus(arg0: Int, arg1: Int): Int{
    return arg0 - arg1
}

fun times(arg0: Int, arg1: Int): Int{
    return arg0 * arg1
}

fun div(arg0: Int, arg1: Int): Int{
    return arg0 / arg1
}

fun showHelp(){
    println("""
        
        Simple Calculator:
            Input: 3 * 4
            Output: 12
    """.trimIndent())
}

你可能感兴趣的:(kotlin从入门到精通,kotlin,java,开发语言)