美文网首页
Kotlin系列之一:初识Kotlin

Kotlin系列之一:初识Kotlin

作者: RookieRun | 来源:发表于2020-03-17 20:33 被阅读0次

初识Kotlin

一.Kotlin的第一次见面

1.Kotlin的HelloWorld

新建一个Kotlin的class,然后一个 main方法就好
    class Test {
    }
    fun main(){
        println("hello world")
    }

疑问:这里可以脱离类的结构运行,比如,我上面新建的是Test.kt,但是我的代码里面却没有类似Java的类结构,Java的结构应该是:

    public class Test {
        public static void main(String []args){
            System.out.println("hello world");
        }
    }

但是,模仿上面java的结构,到Test.kt中时,main方法去无法执行了:

    class Test {
        fun main(){
                println("hello world")
            }
    }

2.方法定义:

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

解释:两个Int类型的参数a,b,一个Int类型的返回值
fun sum(a: Int, b: Int) = (a + b)
解释:将表达式作为函数体,可以省略返回值类型,由程序自动推断

    fun sum1(a:Int,b:Int):Unit{
        println("sum of $a and $b is ${a+b}")
    }

解释:$居然可以在“”里面拿到变量的值!

3.变量定义

1.Java中的new关键字不再用了!
2.关键字
    2.1 val相当于Java里面的 final ,不允许二次赋值
        val a=5//自动推断变量类型
        val a:Int//延迟赋值,需要指定变量类型
    2.2 var //可变类型,适用于全局变量&局部变量

4.字符串模板

    fun changeValue() {
        var a: Int = 1;
        val s1 = "a is $a"
        a += 2
        val s2 = "${s1.replace("is", "was")},now the value is $a"
        println(s2)
    }

5.条件表达式

    fun ifStatment1(a: Int, b: Int): Int {
        if (a>b){
            return a
        }else{
            return b
        }
    }
    //省略版
    fun ifStatment(a:Int,b:Int):Int=if (a>b) a else b

6.空值与null检测

Kotlin是空安全的,那是怎么保证的呢?

1.当某个变量可以为null的时候,必须再声明的后面加?来表示该引用可以为空

    fun parseInt(string: String): Int? {
        try {
            return string.toInt()
        } catch (e: Exception) {
            return null
        }
    }

解释:如果上面的返回值后没有?,则不可以返回null,否则会提示:Null can not be a value of non-null type Int

### 2.if not null
    fun testIfNotNull() {
        var item = "123"
        var toList = item.toList()
        println(toList?.size)
    }
    与上面等价的Java代码是:
    public static void testIfNotNull() {
        String item = "123";
        char[] toList = item.toCharArray();
        if (toList != null) {
            System.out.println(toList.length);
        }
    }
###3.if not null and else
    fun testIfNotNullAndElse() {
        var item = "123"
        var toList = item.toList()
        println(toList?.size ?: "toList 对象为空")
    }
    与上面等价的Java代码是:
    public static void testIfNotNullAndElse() {
        String item = "123";
        char[] toList = item.toCharArray();
        if (toList != null) {
            System.out.println(toList.length);
        } else {
            System.out.println("toList 对象为空");
        }
    }

7.for 循环

    fun forLoop() {
        val list: List<String> = listOf<String>("1", "2", "3")//只读list
        for (item in list) {
            //打印item
            println(item)
        }
        for (index in list.indices){
            //打印index
            println(index)
            //打印item
            println(list.get(index))
        }
    }

8.while 循环

    fun testWhile() {
        val items = listOf("apple", "banana", "kiwifruit")
        var index = 0
        while (index < items.size) {
            println("item at $index is ${items[index]}")
            index++
        }
    }

9.map 遍历

    fun testMap() {
        var map = mapOf("a" to 1, "b" to 2)
        println(map.keys)
        println(map.values)
        println("-----")
        for (key in map.keys) {
            println("key $key")
            println("value " + map[key])
            println("key is $key and value  is ${map[key]}")
        }
        println("-----")
        for ((key, value) in map) {
            println("key $key")
            println("value $value")
        }
        println("-----")
        map.forEach {
            println(it.key)
            println(it.value)
        }
    
    }

10.与Java不一样的几个小例子(java代码就不提供了)

###1.交换两个数值
        fun changeTwoValue() {
            var a = 1
            var b = 2
            a = b.also { b = a }
            println("a =$a and b=$b")
        }
###2. 单表达式函数
    fun theAnswer() = 10
    与上面等价的Kotlin代码是:
        fun testSingleExpression(): Int {
            return 10
        }

二.Kotlin的编码规范

1.命名规范
1)文件命名(类与对象的名称):使用首字母大写的驼峰⻛格:FirstKotlinDemo.kt
2)类结构内部的代码块的顺序:
属性/初始化代码-》次构造函数-》方法-》伴生对象
不要按字母顺序排列方法,而是按照代码的相关性排列方法
如果由内部类,则将内部类至于紧跟使用该内部类代码的后面,如果没有代码使用,则放到类结构的最末尾
3)包名:小写并且不使用下划线
4)函数名,属性名,方法名,局部变量:首字母小写的驼峰而且不使用下划线
5)常量:全大写
2.与Java最大的不同:尽可能的省略;

三.疑问

1.Kotlin中文件名与类名是什么关系?好像可以不一样

相关文章

网友评论

      本文标题:Kotlin系列之一:初识Kotlin

      本文链接:https://www.haomeiwen.com/subject/fxpxyhtx.html