• kotlin函数


    一、Main函数

    fun printHello() {
         println("Hello World")
     }
     printHello()
    Hello World
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在main的函数中,执行播放按钮,会编译执行,结果在下面显示:
    在这里插入图片描述

    1.1 Basic Task

    1. Create a new Kotlin file.
    2. Copy and paste the main() function from Hello World into the file.
    3. Create a new function, dayOfWeek().
    4. In the body of the function, print “What day is it today?”
    5. Call dayOfWeek() from main().
    6. Run your program.
    fun main(args: Array<String> ){
        println("Hello World!")
        dayOfWeek()
    }
    
    fun dayOfWeek() {
        print("What day is it today?")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    1.2 Extended Task

    In the body of the dayOfWeek() function, answer the question by printing the current day of the week.

    Hints

    • You can use Java libraries (java.util) from Kotlin. For example, to get the day of the week:
      Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
    • Type in the code, then press Option + Enter in Mac, or Alt + Enter in Windows, over the red Calendar class to import the library.
    • Use a when statement to print a string depending on the day. Sunday is the first day of the week.
    import java.util.Calendar
    
    fun main(args: Array<String> ){
        println("Hello World!")
        dayOfWeek()
    }
    
    fun dayOfWeek() {
        println("What day is it today?")
        val dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
    //    print(dayOfWeek)
        when(dayOfWeek) {
            1 -> println("Monday")
            2 -> println("Tuesday")
            3 -> println("Wednesday")
            4 -> println("Thursday")
            5 -> println("Friday")
            6 -> println("Saturday")
            7 -> println("Sunday")
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    二、函数参数

    fun main(args: Array<String>) {
        println("Hello ${args[0]}")
    
        val isUnit = println("This is an expression")
        println(isUnit)
    
        val temperature = 10
        val isHot = if (temperature > 50) true else false
        println(isHot)
        
        val message = "You are ${ if (temperature > 50) "fried" else "safe" } fish"
        println(message)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2.1 Greetings, Kotlin

    Exercise: Greetings, Kotlin

    Create a main() function that takes an argument representing the time in 24-hour format (values between and including 0 -> 23).

    In the main() function, check if the time is before midday (<12), then print “Good morning, Kotlin”; otherwise, print “Good night, Kotlin”.

    Notes:

    Remember that all main() function arguments are Strings, so you will have to convert this argument to an Int before you can apply the check.

    fun main(args: Array<String>)
    {
        if( args[0].toInt() < 12) {
            println("Good morning,Kotlin")
        } else if( args[0].toInt() in 12..24) {
            println("Good night,Kotlin")
        } else {
            println("Error time")
        }
    
        println("Good ${if(args[0].toInt() > 12) "night" else "morning"},Kotlin")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    三、随机日子喂鱼

    import java.util.*
    
    fun main(args: Array<String> ){
        println("Hello World!")
        feedTheFish()
    }
    
    fun feedTheFish() {
        val day = randomDay()
        val food = "pellets"
        println("Today is $day and fish eat $food")
    }
    
    fun randomDay() : String {
        val week = listOf("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
        return week[Random().nextInt(7)]
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3.1 练习

    Create a program with a function that returns a fortune cookie message that you can print.

    1. Create a main() function.
    2. From the main() function, call a function, getFortuneCookie(), that returns a String.
    3. Create a getFortuneCookie() function that takes no arguments and returns a String.
    4. In the body of getFortuneCookie(), create a list of fortunes. Here are some ideas:
      • “You will have a great day!”
      • “Things will go well for you today.”
      • “Enjoy a wonderful day of success.”
      • “Be humble and all will turn out well.”
      • “Today is a good day for exercising restraint.”
      • “Take it easy and enjoy life!”
      • “Treasure your friends because they are your greatest fortune.”
    5. Below the list, print: "Enter your birthday: "
      • Hint: Use print(), not println()
    6. Create a variable, birthday.
    7. Read the user’s input form the standard input and assign it to birthday. If there is no valid input, set birthday to 1.
      • Hint: Use readLine() to read a line of input (completed with Enter) as a String.
      • Hint: In Kotlin, you can use toIntOrNull() to convert a number as a String to an Integer numeric. If the user enters “”, toIntOrNull returns null.
      • Hint: Check for null using the ? operator and use the ?: operator to handle the null case.
    8. Divide the birthday by the number of fortunes, and use the remainder as the index for the fortune to return.
    9. Return the fortune.
    10. In main(), print: "Your fortune is: ", followed by the fortune string.
      Extra practice:
      Use a for loop to run the program 10 times, or until the “Take it easy” fortune has been selected.
    fun main(args:Array<String>)
    {
        var fortune = getFortuneCookie()
        println("Your fortune is:$fortune")
    }
    
    fun getFortuneCookie() : String
    {
        val fortunesList:Array<String> = arrayOf("You will have a great day!",
            "Things will go well for you today.", "Enjoy a wonderful day fo success.",
            "Be humble and all will turn out well.", "Today is good day for exercising restraint.",
            "Take it easy and enjoy life!", "Treasure your friends because they are your greatest fortune.")
    
        print("enter your birthday:")
        var birthday:Int = readLine()?.toIntOrNull()?:1
        var fortuneNum:Int = birthday.mod(7)
        return fortunesList[fortuneNum];
    }
    
    
    //结果:
    //enter your birthday:14
    //Your fortune is:You will have a great day!
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3.2 extra练习:

    fun main(args:Array<String>)
    {
        //var fortuneNum = getFortuneCookie()
        //println("Your fortune is:${fortuneNum}")
        var fortune: String
        for(i in 1..10) {
            fortune = getFortuneCookie()
            println("Your fortune is: $fortune")
            if(fortune.contains("Take it easy")) break
        }
    
    }
    
    fun getFortuneCookie() : String
    {
        val fortunesList:Array<String> = arrayOf("You will have a great day!",
            "Things will go well for you today.", "Enjoy a wonderful day fo success.",
            "Be humble and all will turn out well.", "Today is good day for exercising restraint.",
            "Take it easy and enjoy life!", "Treasure your friends because they are your greatest fortune.")
    
        print("enter your birthday:")
        var birthday:Int = readLine()?.toIntOrNull()?:1
        var fortuneNum:Int = birthday.rem(fortunesList.size)
        return fortunesList[fortuneNum];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    四、when函数可以简化

    fun fishFood(day: String) : String {
        var food = "fasting"
    
        return when(day) {
            "Monday" -> food = "flakes"
            "Tuesday" -> food = "pellets"
            "Wednesday" -> food = "redworms"
            "Thursday" -> food = "granules"
            "Friday" -> food = "mosquitoes"
            "Saturday" -> food = "lettuce"
            "Sunday" -> food = "plankton"
        }
        return food
    }
    //可以改成
    fun fishFood(day: String) : String {
        return when(day) {
            "Monday" -> "flakes"
            "Tuesday" -> "pellets"
            "Wednesday" -> "redworms"
            "Thursday" -> "granules"
            "Friday" -> "mosquitoes"
            "Saturday" -> "lettuce"
            "Sunday" -> "plankton"
            else -> "fasting"
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    4.1 练习习题

    Use the code you created in the last practice, or copy the starter code from below.

    The getFortune() function should really only be getting the fortune, and not be in the business of getting the birthday.

    Change your Fortune Cookie program as follows:

    Create a function called getBirthday() that gets the birthday from the user.
    Pass the result of getBirthday() to getFortune() using an Integer argument, and use it to return the correct fortune.
    Remove getting the birthday from getFortune()
    Instead of calculating the fortune based on the birthday, use a when statement to assign some fortunes as follows (or use your own conditions):
    If the birthday is 28 or 31…
    If the birthday is in the first week…
    else … return the calculated fortune as before.
    Hint: There are several ways in which to make this when statement. How much can you Kotlinize it?

    Starter Code:

    fun main(args: Array) {
    var fortune: String
    for (i in 1…10) {
    fortune = getFortune(getBirthday())
    println(“\nYour fortune is: $fortune”)
    if (fortune.contains(“Take it easy”)) break;
    }
    }

    fun main(args:Array<String>)
    {
        var fortune: String
        for(i in 1..10) {
            fortune = getFortune(getBirthday())
            println("Your fortune is: $fortune")
            if(fortune.contains("Take it easy")) break
        }
    
    }
    
    fun getFortune(birthday: Int) : String
    {
        val fortunesList:Array<String> = arrayOf("You will have a great day!",
            "Things will go well for you today.", "Enjoy a wonderful day fo success.",
            "Be humble and all will turn out well.", "Today is good day for exercising restraint.",
            "Take it easy and enjoy life!", "Treasure your friends because they are your greatest fortune.")
        val index = when(birthday) {
            in 28..31 -> 3
            1,7 -> 2
            else -> birthday.rem(fortunesList.size)
        }
        return fortunesList[index];
    }
    
    fun getBirthday(): Int {
        print("enter your birthday:")
        return readLine()?.toIntOrNull() ?: 1
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    5. 函数参数可以有默认值

    fun swim(speed: String = "fast") {
        println("swimming $speed")
    }
    //调用swim()时,如果没有参数,就是fast
    //也可以混合,可以多个参数,可以指定
    
    • 1
    • 2
    • 3
    • 4
    • 5

    5.1 练习

    Exercise: Fit More Fish
    Create a function that checks if we can add another fish into a tank that already has fish in it.

    How many fish in a tank?
    The most widely known rule for stocking a tank is the one-inch-per-fish-per-gallon-of-water rule. However that’s assuming the tank doesn’t have any decorations in it.

    Typically, a tank with decorations can contain a total length of fish (in inches) less than or equal to 80% of the tank size (in gallons). A tank without decorations can contain a total length of fish up to 100% of the tank size.

    For example:
    A 10 gallon tank with decorations can hold up to 8 inches of fish, for example 4 x 2-inch-long fish.
    A 20 gallon tank without decorations can hold up to 20 inches of fish, for example 6 x 1-inch-long fish and 2 x 2-inch-long fish.
    fitMoreFish function
    Create a function that takes these arguments:

    tankSize (in gallons)
    currentFish (a list of Ints representing the length of each fish currently in the tank)
    fishSize (the length of the new fish we want to add to the tank)
    hasDecorations (true if the the tank has decorations, false if not)
    You can assume that typically a tank has decorations, and that a typical fish is 2 inches long. That means you can set those values as default parameters.

    Output
    Make sure you test your code against the following calls, and that you get the correct output for each.

    canAddFish(10.0, listOf(3,3,3)) —> false
    canAddFish(8.0, listOf(2,2,2), hasDecorations = false) —> true
    canAddFish(9.0, listOf(1,1,3), 3) —> false
    canAddFish(10.0, listOf(), 7, true) —> true

    import java.util.*
    
    fun main() {
        println(canAddFish(10.0, listOf(3,3,3)))
        println(canAddFish(8.0, listOf(2,2,2), hasDecorations = false))
        println(canAddFish(9.0, listOf(1,1,3), 3))
        println(canAddFish(10.0, listOf(), 7, true))
    }
    
    fun canAddFish(tankSize:Double, currentFish:List<Int>, fishSize:Int = 2, hasDecorations:Boolean = true): Boolean
    {
        return ((tankSize * if(hasDecorations) 0.8 else 1.0 )>= (currentFish.sum() + fishSize))
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    Practice Time
    Create a program that suggests an activity based on various parameters.

    Start in a new file with a main function.
    From main(), create a function, whatShouldIDoToday().
    Let the function have three parameters.
    mood: a required string parameter
    weather: a string parameter that defaults to “sunny”
    temperature: an Integer parameter that defaults to 24 (Celsius).
    Use a when construct to return some activities based on combinations of conditions. For example:
    mood == “happy” && weather == “Sunny” -> “go for a walk”
    else -> “Stay home and read.”
    Copy/paste your finished function into REPL, and call it with combinations of arguments. For example:
    whatShouldIDoToday(“sad”)
    > Stay home and read.

    fun main()
    {
        println(whatShouldDoToday("sad"))
    }
    
    fun whatShouldDoToday(mood:String, weather: String = "Sunny", temperature:Int=24) : String
    {
        return if(mood == "happy" && weather == "Sunny") "go for a walk"
        else "Stay home and read."
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Improve your whatShouldIDoToday() program with the new knowledge from this segment.

    Add 3 more situations and activities. For example:
    mood == “sad” && weather == “rainy” && temperature == 0 -> “stay in bed”
    temperature > 35 -> “go swimming”
    Create a single-expression function for each condition and then use it in your when expression.
    Challenge
    Instead of passing in the mood, get a mood string from the user.

    Hint: The !! operator may come handy.

    Loops
    This lesson introduced the while and repeat loops. To practice using them, do the following:

    Change your fortune cookie program to use repeat() instead of a for loop. What happens to the break instruction? Using the error message from the compiler, with what you’ve learned so far, can you think of why?
    Change your fortune cookie program to use a while loop, which is the better choice when you are looping until a condition is met.

    fun main()
    {
        println(whatShouldDoToday("sad"))
        println(whatShouldDoToday("sad", "rainy", 0))
        println(whatShouldDoToday(weather = "rainy", temperature = 0))
    }
    
    fun getMood() = "sad"
    
    fun whatShouldDoToday(mood:String = getMood(), weather: String = "Sunny", temperature:Int=24) : String
    {
        return when {
            mood == "happy" && weather == "Sunny" -> "go for a walk"
            mood == "sad" && weather == "rainy" && temperature == 0 -> "stay in bed"
            temperature > 35 -> "go swimming"
            else -> "Stay home and read."
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    使用循环的练习

    fun main(args:Array<String>)
    {
        var fortune: String = ""
    //    repeat(10) {
            while(!fortune.contains("Take it easy")) {
    //    for(i in 1..10) {
            fortune = getFortune(getBirthday())
            println("Your fortune is: $fortune")
    //        if(fortune.contains("Take it easy")) break
        }
    
    }
    
    fun getFortune(birthday: Int) : String
    {
        val fortunesList:Array<String> = arrayOf("You will have a great day!",
            "Things will go well for you today.", "Enjoy a wonderful day fo success.",
            "Be humble and all will turn out well.", "Today is good day for exercising restraint.",
            "Take it easy and enjoy life!", "Treasure your friends because they are your greatest fortune.")
        val index = when(birthday) {
            in 28..31 -> 3
            1,7 -> 2
            else -> birthday.rem(fortunesList.size)
        }
        return fortunesList[index];
    }
    
    fun getBirthday(): Int {
        print("enter your birthday:")
        return readLine()?.toIntOrNull() ?: 1
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    六、过滤

    fun main()
    {
        val list = listOf("abc", "ghf", "aaa", "tur")
        println(list.filter { it[0] == 'a' })
    //    eagerExample()
    //    lazilyExample()
        lazilyMapExample()
    }
    
    fun eagerExample() {
        var list = listOf("rock", "pagoda", "plastic", "tur")
        val decorations = list.filter { it[0] == 'p' }
        println(decorations)
    }
    
    fun lazilyExample() {
        var list = listOf("rock", "pagoda", "plastic", "tur")
        val decorations = list.asSequence().filter { it[0] == 'p' }
        println(decorations)
        println(decorations.toList())
    }
    
    fun lazilyMapExample() {
        println("lazilyMapExample")
        var list = listOf("rock", "pagoda", "plastic", "tur")
        val decorations = list.asSequence().filter { it[0] == 'p' }
        val lazyMap = decorations.asSequence().map {
            println("map $it")
            it
        }
        println("lazyMap:${lazyMap}")
        println("first:${lazyMap.first()}")
        println("all:${lazyMap.toList()}")
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    Practice Time
    You can do the following filter exercise in REPL.

    Create a list of spices, as follows:
    val spices = listOf(“curry”, “pepper”, “cayenne”, “ginger”, “red curry”, “green curry”, “red pepper” )
    Create a filter that gets all the curries and sorts them by string length.
    Hint: After you type the dot (.), IntelliJ will give you a list of functions you can apply.
    Filter the list of spices to return all the spices that start with ‘c’ and end in ‘e’. Do it in two different ways.
    Take the first three elements of the list and return the ones that start with ‘c’.
    Note: We will be able to do a lot more interesting stuff with filters after you learn about classes and Map.

    val spices = listOf("curry", "pepper", "cayenne", "ginger", "red curry", "green curry", "red pepper")
    
    println(spices.filter { it[0] == 'c' && it[it.length-1] == 'e' })
    println(spices.filter { it[0] == 'c' && it.endsWith('e')})
    println(spices.take(3).filter { it.startsWith('c') })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    七、Lambda

    {println("Hello")}()
    Hello
    
        val swim = {println("swim\n")}
        swim()
    swin
    
    var dirty = 4
     val waterFilter = {dirty: Int -> dirty/2}
     waterFilter(dirty)
    res3: kotlin.Int = 2
    
    
    fun main(args: Array<String> ){
        println("Hello World!")
    
        var swimDontRun = {println("swim\n")}
        var swimRunDirectly = { println("swim") }()
        var swimRunDirectly2 = run { println("swim") }
    
        swimDontRun()
        swimRunDirectly
        swimRunDirectly2
    
    
        var dirty = 20
        var waterFilter = {dirty:Int -> dirty /2}
        println(waterFilter(dirty))
    
        val waterFilter2: (Int) -> Int = {abc : Int -> abc + 2}
        val waterFilter3: (Int) -> Int = {abc -> abc + 2 }
        val waterFilter4: (Int) -> Int = { whatever -> whatever*2}
    
        println(waterFilter2(dirty))
        println(waterFilter3(dirty))
        println(waterFilter4(dirty))
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    Practice Time: Lambdas
    Create a lambda and assign it to rollDice, which returns a dice roll (number between 1 and 12).
    Extend the lambda to take an argument indicating the number of sides of the dice used for the roll.
    If you haven’t done so, fix the lambda to return 0 if the number of sides passed in is 0.
    Create a new variable, rollDice2, for this same lambda using the function type notation.

    val rollDice = { Random().nextInt(12) + 1 }
    val rollDice2 = {sides:Int -> Random().nextInt(sides) + 1}
    val rollDice3 = {sides:Int -> if(sides == 0) 0 else Random().nextInt(sides) + 1 }
    val rollDice4: (Int) -> Int = {sides -> Random().nextInt(sides) + 1}
    
    • 1
    • 2
    • 3
    • 4

    Practice Time: Extra Questions
    Why would you want to use the function type notation instead of just the lambda?
    Create a function gamePlay() that takes a roll of the dice as an argument and prints it out.
    Pass your rollDice2 function as an argument to gamePlay() to generate a dice roll every time gamePlay() is called

        val dice = {sides:Int -> Random().nextInt(sides) + 1}
        val rollDice2:(Int) -> Int = {sides:Int -> if(sides == 0) 0 else Random().nextInt(sides) + 1 }
        gamePlay(dice, rollDice2)
    
    • 1
    • 2
    • 3
  • 相关阅读:
    PowerQuery领域的经典之作“猴子书“中文版来啦!
    go的数据类型
    Mysql 安装与卸载
    自然语言处理 中文停用词词典
    K8S:K8S自动化运维容器Docker集群
    算法详解——贪心算法
    javamail——邮件发送
    SuperMap iManager for K8S使用XFS文件系统类型出现节点异常解决办法
    图像处理: 马赛克艺术
    异步并发怎么做?
  • 原文地址:https://blog.csdn.net/ch122633/article/details/127672973