kotlin这一篇就够了

218 阅读2分钟
  • 1、data类型的类
data class Customer(val name: String, val email: String)

getters (and setters in case of vars) for all properties
equals()
hashCode()
toString()
copy()
  • 2、函数的默认值
fun foo(a: Int = 0, b: String = "") { ... }
  • 3、集合过滤
val positives = list.filter { x -> x > 0 }

val positives = list.filter { it > 0 }
  • 4、字符串插入
val name ="xx"
println("Name $name")
  • 5、when 代替 switch
when (x) {
    1-> ...
    2-> ...
    else   -> ...
}
  • 6、for循环
for ((k, v) in map) {
    println("$k -> $v")
}
for (i in 1..100) { ... }  // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
  • 7、获取map
val list = listOf("a", "b", "c")
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
println(map["key"])
map["key"] = value

  • 8、延迟属性
val lazyValue: String by lazy {
    println("computed!")
    "Hello"
}

fun main(args: Array<String>) {
    println(lazyValue)
    println(lazyValue)
}


computed!
Hello
Hello
  • 9、拓展函数
 fun Activity.toast(str:String){
        Toast.makeText(applicationContext,str,Toast.LENGTH_SHORT).show()
    }
	
 tv_splash_jump.setOnClickListener({
            toast("hello")
        })
  • 10、单例
  object Singleton
  • 11、兼容null ?
    val map = mapOf("a" to 1, "b" to 2, "c" to 3)

	var testNul = map["d"]
	println(testNul)
	println(testNul ?: "empty")
	val d = testNul ?: throw IllegalStateException("d is missing!")
	
System.out: null
System.out: empty
java.lang.IllegalStateException: d is missing!
  • 12、when
fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}

  • 12、单行函数
fun sum(a:Int,b:Int) = a+b
  • 13、多行函数
fun sum(a: Int, b: Int): Int {
    return a + b
}

fun transform(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Blue" -> 2
    else -> throw IllegalArgumentException("Invalid color param value")
}
  • 14、Unit代替java中的void
fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}
  • 15 交换两个数
var a = 1
var b = 2
a = b.also { b = a }
  • 15 let函数
object.let{
   it.todo()//在函数体内使用it替代object对象去访问其公有的属性和方法
   ...
}

//另一种用途 判断object为null的操作
object?.let{//表示object不为null的条件下,才会去执行let函数体
   it.todo()
}
  • 16、接口回调的优化
tv_splash_jump.setOnClickListener({
		view:View ->

})
tv_splash_jump.setOnClickListener({
	view ->

})
tv_splash_jump.setOnClickListener{

}
  • 17、var val const
const val MIN_ALPHA = 0.5f
private const val MIN_ALPHA_FIRST = 0.5f
val MIN_ALPHA_SECOND = 0.5f
var MIN_ALPHA_THIRD = 0.5f
class Student(var name: String = "", var age: Int = 0) {
    val MIN_ALPHA_FOUR = 0.5f
    var MIN_ALPHA_FIVE = 0.5f
    
}


// access flags 0x19
public final static F MIN_ALPHA = 0.5

// access flags 0x1A
private final static F MIN_ALPHA_FIRST = 0.5

// access flags 0x1A
private final static F MIN_ALPHA_SECOND = 0.5

// access flags 0xA
private static F MIN_ALPHA_THIRD

// access flags 0x12
private final F MIN_ALPHA_FOUR = 0.5
// access flags 0x2
private F MIN_ALPHA_FIVE
  • 18、修饰符
public / protected / private / internal   //默认为public
expect / actual
final / open / abstract / sealed / const
external
override
lateinit
tailrec
vararg
suspend
inner
enum / annotation
companion
inline
infix
operator
data
  • 19、数据类型
类型 位宽度
Byte 8
Short 16
Int 32
Long 64
Float 32
Double 64

** char已经不是数字类型啦 可以通过下划线优化显示**

val oneMillion = 1_000_000
val creditCardNumber = 1234_5678_9012_3456L
val socialSecurityNumber = 999_99_9999L
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010
// if 带有返回值  所以没有三目运算符
val max = if (a > b) a else b

// when 代替switch case
when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}
//可以使用in表达式
when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}

//循环
for (i in 6 downTo 0 step 2) {
    println(i)
}
  • 21、返回值
loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
    }
}
  • 22、解构声明
var person: Person = Person("Jone", 20)
var (name, age) = person

println("name: $name, age: $age")// 打印:name: Jone, age: 20