Zorgan
Zorgan

Reputation: 9123

Lambda expression inside Kotlin String

My code:

class Team (val name: String, val aggressive: Boolean = true) {

    val attendance: Int

    init {
        if (aggressive){
            attendance = 25000
        } else {
            attendance = 20000
        }
    }

}

...

fun chooseTeam() {
    val homeTeam = Team(name = "Everton")
    println("the home team is $homeTeam.aggressive so they are ${if ($homeTeam == "aggressive") "angry" else "timid" }") 
}

I'm trying to assign the value of the lambda string based on if $homeTeam.aggressive is true or not.

However I'm getting red lines all over the lambda so obviously the syntax seems off. Can someone tell me whats wrong with the code?

Upvotes: 0

Views: 205

Answers (2)

Suyash Chavan
Suyash Chavan

Reputation: 735

The correct way

fun chooseTeam() {
    val homeTeam = Team(name = "Everton")

    // 1) no dollar sign before homeTeam in the comparison 
    // 2) in kotlin if you declare constructor parameter as val they also becomes property of class which you can access like this homeTeam.aggressive
    // 2) if you want the name of team, just use ${homeTeam.name} instead $homeTeam.aggression
    println("the home team is $homeTeam.aggression so they are ${if(homeTeam.aggressive) "angry" else "timid"}") 
}

Hope this helps.

Edit : More detailed explanation is given by @Willi Mentzel

Upvotes: -1

Willi Mentzel
Willi Mentzel

Reputation: 29844

What you actually mean is a string template and not a lambda. You must have confused it because both use curly brackets {...}.

You can either do it like this:

fun chooseTeam() {
    val homeTeam = Team(name = "Everton")

    // 1) no dollar sign before homeTeam in the comparison
    // 2) you need to compare to homeTeam.aggressive and not homeTeam
    println("the home team is ${homeTeam.name} so they are ${if (homeTeam.aggressive) "angry" else "timid" }")
}

Or better, you assign the mapping (Boolean to String) to a variable first which increases the readability.

fun chooseTeam() {
    val homeTeam = Team(name = "Everton")
    val adjective = if (homeTeam.aggressive) "angry" else "timid"

    println("the home team is ${homeTeam.name} so they are $adjective")
}

Upvotes: 5

Related Questions