某人整理的csdn的kotlin地址:https://www.cnblogs.com/Jetictors/tag/Kotlin/
for (i in 1..10)
for (i in 1 until 10)
for (i in 10 downTo 1 step 1)
var binaryMap = TreeMap
binaryMap['A']="A"
for ((letter, binary) in binaryMap) { ... }
val list = arrayListOf
for((index, element) in list.withIndex()) { ... }
val result = try {
Integer.parseInt(i)
} catch (e: NumberFormatException) {
null
}
val str = if (true) "true" else "false"
fun max3(a:Int, b:Int) = if(a > b) a else b
fun getMnemonic(color: Color) = when (color) {
Color.RED -> "RED"
Color.ORANGE -> "ORANGE"
Color.YELLOW -> "YELLOW"
Color.GREEN -> "GREEN"
Color.BLUE -> "BLUE"
Color.WHITE -> "WHITE"
}
fun getWarmth(color: Color) = when (color) {
Color.RED, Color.BLUE, Color.GREEN -> "Wram"
Color.ORANGE, Color.WHITE, Color.YELLOW -> "Colder"
}
fun fizzBuzz(i: Int) = when {
i % 3 == 0 -> "Pizz"
i % 5 == 0 -> "Buzz"
i % 15 ==0 -> "PizzBuzz"
else -> "$i"
}
interface Expr
class Num(val value: Int): Expr // 实现了接口
// 三重引号的字符串(正则表达式放在三重引号的字符串中,其中字符不需转义.而不是\.)
val regex = """(.+)/(.+).(.+)""".toRegex()
val matchResult = regex.matchEntire(path)
if (matchResult != null) {
val (dictory, filename, extension) = matchResult.destructured
println("lists: filename, $extension")
}
/*
可变属性setter设定为私有
-
*/
class LengthCounter {
var counter:Int = 0
private setfun addWord(word: String) {
counter += word.length
}
}
// data作为修饰符说明其已经实现了toString,equals,hashCode
data class Client2(val name:String, val postalCode: Int) {}
object Payroll {} // 单例 Java调用Payroll.INSTANCE.xxx
companion object Payroll {} // 静态对象 Java调用Payroll.Companion.xxx, 类似于静态类
// 伴生对象就是类似java中的static,允许类内有静态函数或变量的存在!
// object表示其是一个静态类,后不要再跟class了
# 单例
fun main(args: Array) {
println(Utils.instance.name) // 此处instance已被作为类的静态对象调用
}
class Utils private constructor() {
fun sayHello()
{
println("hello")
}
var name="张三"
var age=20
companion object {
val instance by lazy { Utils() }
}
}
with() apply {}
?. ?: as? !! let{ ... } lateinit
Any, Unit, Nothing(常用于异常作为返回值,表示其不会正常终止)
Collection(只读)
MutableCollections(读写)
arrayOf(数组)
数组遍历:
Array(5) {"item-"+(1+it)}.forEachIndexed { index, s -> println("$TAG index:$index,content: $s") }
use
inline reified
fun
out(协变), in(逆变), (类型投影)
Lambda的调用.invoke()