class Test(var name: String) { fun naming() { name = "John" } }
kotlin
class Test(name: String) { fun naming() { name = "John" // 错误 } }
kotlin
class Person( val firstName: String, val lastName: String, var age: Int, )
kotlin
open class Test(name: String) { }
kotlin
class TestSub : Test("Hello") { }
kotlin
class MainActivity : ComponentActivity() { }
kotlin
{ 参数 -> 要执行的代码 }
kotlin
val doubleIt = { number: Int -> number * 2 } val result = doubleIt(8) // 16
kotlin
{ number: Int -> number * 2 }
kotlin
fun addNumbers(num1: Int, num2: Int): Int { return num1 + num2 }
kotlin
{ num1: Int, num2: Int -> num1 + num2 }
kotlin
(Int) -> Int
kotlin
fun calculate(num: Int, doubleIt: (Int) -> Int): Int { val result = doubleIt(num) return result }
kotlin
val result1 = calculate(7, { x: Int -> x * 2 }) val result2 = calculate(7) { x: Int -> x * 2 } val result3 = calculate(7) { it * 2 } val result4 = calculate(7, doubleIt = { it * 2 })
kotlin
fun calculate(num: Int, action: (Int) -> Int): Int { return action(num) }
fun main() { val a = calculate(7) { it * 2 } val b = calculate(7) { it + 3 } val c = calculate(7) { it * it }
// 还是把字符串转换成大写 // 这种写法先做非空判断,再决定怎么处理,更安全,也更容易理解 // 如果传入 null,就返回空字符串 "" fun changeToUpperCase2(word: String?): String { var result = ""
if (word != null) result = word.uppercase()
return result }
// 返回字符串长度 // 参数允许为 null,但这里用了 !! 强制非空 // 所以如果传入 null,会报错 fun wordLength(word: String?): Int { return word!!.length }
// 高阶函数示例 // doubleIt 不是普通参数,而是一个函数类型参数 // (Int) -> Int 的意思是: // 传入一个 Int,返回一个 Int // // 这里会把类里的 num 传给 doubleIt 这个函数去处理 // 比如 num = 7,传入 { it * 2 },结果就是 14 fun calculate(doubleIt: (Int) -> Int): Int { val result = doubleIt(num) return result } }
kotlin
val calculator = Calculation(7)
val result = calculator.calculate { it * 2 } // 14 val result2 = calculator.changeToUpperCase("hello") // HELLO val result3 = calculator.wordLength("hello") // 5 val result4 = calculator.echoThis(5) // 15
kotlin
@Composable fun Greeting(name: String) { Text("Hello$name") }
kotlin
@Preview(showBackground = true) @Composable fun PreviewDisplayMessage() { DisplayMessage("FIT5046") }
kotlin
@Composable fun ColumnTest() { Column( modifier = Modifier.padding(24.dp) ) { Text("the first Text") Text("the second Text") } }
kotlin
@Composable fun RowAndColumn() { Row(verticalAlignment = Alignment.CenterVertically) { Icon( imageVector = Icons.Default.Person, contentDescription = "Person" ) Column { Text("the first Text") Text("the second Text") } } }