美文网首页
Kotlin相关

Kotlin相关

作者: 是y狗阿 | 来源:发表于2017-05-26 17:47 被阅读0次

Kotlin安装

Android Studio

Idea

Kotlin使用

  • var关键字声明可变属性,val关键字声明只读属性

  • 函数参数在声明的时候可以设置默认值,当参数被忽略的时候后会使用默认值。比其他语言更加方便。减少了重载。

     fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size()){
         ...
     }
    
  • 还可以在函数中命名多个参数,但只选取部分使用。
    fun reformat(str: String, normalizeCsase: Boolean = true, upperCaseFirstLetter: Boolean = true, divideByCamelHumps: Boolean = false, wordSeparator: Char = ' '){
    ...
    }
    可以使用默认参数:
    reformat(str)
    也可以调用非默认参数:
    remormat(str, true, true, false, '')
    也可以使用命名对应,让代码的可读性更强:
    reformat(
    str,
    normalizeCase = true,
    uppercaseFirstLetter = true,
    divideByCamelHumps = false,
    wordSeparator = '
    ')
    如果不需要全部参数的话可以这样:
    reformat(str, wordSeparaptor = '__')
    注意,命名参数语法不能够用于调用Java函数中,因为Java的字节码不能保证参数命名的不变形。

  • 可空类型和非可空类型
    Kotlin类型致力于消灭空引用。
    在Kotlin类型系统中可为空和不可为空的引用是不同的。
    val a: String = "abc" //不允许为空
    val b: String? = "abc" //允许为空
    val l = a.length //允许
    val l = b.length //报错
    条件检查null
    val l = if (b != null) b.length else -1
  • list或者array的索引进行迭代,可以使用:
    for(I in array.indices){
    print(array[I])
    }
    或者:
    for((index, value) in array.withIndex()){
    println(the element at $index )
    }

  • 一个抽象类或者函数默认open,所以不需要加。

相关文章

网友评论

      本文标题:Kotlin相关

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