Android 开发 Kotlin学习(二)

82 阅读2分钟

函数

声明函数使用关键词fun

fun hello() {
    return println("Hello, world!")
}
  1. 传参需要声明在函数()内
  2. 多个参数之间使用, 分隔
  3. 函数返回值写在函数末尾使用 :
  4. 返回值需要声明数据类型
  5. 函数内容要写在{} 内
fun sum(x: Int, y: Int): Int {
    return x + y
}

fun main() {
    println(sum(1, 2))
    // 3
}

函数传参默认值

fun printMessageWithPrefix(message: String, prefix: String = "Info") {
    println("[$prefix] $message")
}

fun main() {
    // Function called with both parameters
    printMessageWithPrefix("Hello", "Log") 
    // [Log] Hello
    
    // Function called only with message parameter
    printMessageWithPrefix("Hello")        
    // [Info] Hello
    
    printMessageWithPrefix(prefix = "Log", message = "Hello")
    // [Log] Hello
}

单表达式函数

fun sum(x: Int, y: Int): Int {
    return x + y
}

fun main() {
    println(sum(1, 2))
    // 3
}

可简写为下面

fun sum(x: Int, y: Int) = x + y

fun main() {
    println(sum(1, 2))
    // 3
}

Classes

使用clss声明

属性声明

//1
class Contact(val id: Int, var email: String)

//2
class Contact(val id: Int, var email: String) { val category: String = "" }


//3 默认值
class Contact(val id: Int, var email: String = "example@gmail.com") { val category: String = "work" }

Data classes

Kotlin的数据类对于存储数据特别有用。数据类具有与类相同的功能,但它们会自动附带其他成员函数

data class User(val name: String, val id: Int)
FunctionDescription
.toString()Prints a readable string of the class instance and its properties.
.equals() or ==Compares instances of a class.
.copy()Creates a class instance by copying another, potentially with some different properties.

比较class

val user = User("Alex", 1)
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)

// Compares user to second user
println("user == secondUser: ${user == secondUser}") 
// user == secondUser: true

// Compares user to third user
println("user == thirdUser: ${user == thirdUser}")   
// user == thirdUser: false

复制class

val user = User("Alex", 1)
val secondUser = User("Alex", 1)
val thirdUser = User("Max", 2)

// Creates an exact copy of user
println(user.copy())       
// User(name=Alex, id=1)

// Creates a copy of user with name: "Max"
println(user.copy("Max"))  
// User(name=Max, id=1)

// Creates a copy of user with id: 3
println(user.copy(id = 3)) 
// User(name=Alex, id=3)

空安全

在Kotlin中,可以有一个“null”值。为了防止程序中出现“null”值问题,Kotlin提供了null安全性。Null安全性在编译时而不是运行时检测“Null”值的潜在问题

fun main() {
    // neverNull has String type
    var neverNull: String = "This can't be null"

    // Throws a compiler error
    neverNull = null

    // nullable has nullable String type
    var nullable: String? = "You can keep a null here"

    // This is OK  
    nullable = null

    // By default, null values aren't accepted
    var inferredNonNull = "The compiler assumes non-nullable"

    // Throws a compiler error
    inferredNonNull = null

    // notNull doesn't accept null values
    fun strLength(notNull: String): Int {                 
        return notNull.length
    }

    println(strLength(neverNull)) // 18
    println(strLength(nullable))  // Throws a compiler error
}

常用判断null方法

fun describeString(maybeString: String?): String {
    if (maybeString != null && maybeString.length > 0) {
        return "String of length ${maybeString.length}"
    } else {
        return "Empty or null string"
    }
}

fun main() {
    var nullString: String? = null
    println(describeString(nullString))
    // Empty or null string
}

空安全判断 使用?.

fun lengthString(maybeString: String?): Int? = maybeString?.length

fun main() { 
    var nullString: String? = null
    println(lengthString(nullString))
    // null
}

空安全判断并赋默认值 使用?:

fun main() {
    var nullString: String? = null
    println(nullString?.length ?: 0)
    // 0
}