Home > Back-end >  kotlin fun with string concatenation
kotlin fun with string concatenation

Time:10-16

I need help concatenating a string in a kotlin viewmodel. I am trying to return what the code should print to the status text view. The formula determines from a Int what the status should be then outputs a message to the User. I am unsure as to what method should be used to create a string that I wanted to return.

fun formula(f: Int, b: Int, l: Int, d: Int) : String {
        if (f > 70 && f < 99) {
            val ftxt = "Normal"
        } else if (f < 71) {
            val ftxt = "Hypoglycemic"
        }

        if (b > 140) {
            val btxt = "Abnormal"
        } else if (b < 71) {
            val btxt = "Hypoglycemic"
        }

        if (l > 140) {
            val ltxt = "Abnormal"
        } else if (l < 71) {
            val ltxt = "Hypoglycemic"
        }

        if (d > 140) {
            val dtxt = "Abnormal"
        }else if (d < 71) {
            val dtxt = "Hypoglycemic"
        }
        else {
            val ftxt = "Abnormal"
            val btxt = "Normal"
            val ltxt = "Normal"
            val dtxt = "Normal"
        }
        var status = calendar.toString()
        status  = "\n Fasting: "
        status  = ftxt   "\n Breakfast: "
        status  = btxt   "\n Lunch: "
        status  = ltxt   "\n Dinner: "   dtxt
        return status
    }

Red text

CodePudding user response:

Without entering into detail on how you could improve your function you're having the "red squiggles" because those val are declared within the scope of the if-else blocks.

You can declare them out of the block and assign values:


fun formula(f: Int, b: Int, l: Int, d: Int) : String {
    var ftxt = ""    
    var btxt = ""
    var ltxt = ""
    var dtxt = ""
    if (f > 70 && f < 99) {
        ftxt = "Normal"
    } else if (f < 71) {
        ftxt = "Hypoglycemic"
    }

    if (b > 140) {
        btxt = "Abnormal"
    } else if (b < 71) {
        btxt = "Hypoglycemic"
    }

    if (l > 140) {
        ltxt = "Abnormal"
    } else if (l < 71) {
        ltxt = "Hypoglycemic"
    }

    if (d > 140) {
        dtxt = "Abnormal"
    }else if (d < 71) {
        dtxt = "Hypoglycemic"
    }
    else {
        ftxt = "Abnormal"
        btxt = "Normal"
        ltxt = "Normal"
        dtxt = "Normal"
    }
    var status = calendar.toString()
    status  = "\n Fasting: "
    status  = ftxt   "\n Breakfast: "
    status  = btxt   "\n Lunch: "
    status  = ltxt   "\n Dinner: "   dtxt
    return status
}
  • Related