Click here to Skip to main content
15,885,086 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Kotlin
fun main(){
    val crewCrewCrew = listOf(
        Sloths("Jerry", false,15),
        Panda("Tegan"),
        Manatees("Manny"))
    crewCrewCrew.forEach {
        mammalFactCheck(it, Mammal::vertebraeCount)
        mammalFactCheck(it, Mammal::knownSpeciesCount)

    }
}
sealed class Mammal(val name: String)
    
data class Panda(val pandaName: String): Mammal(pandaName)

data class Sloths(val slothName: String,
                 val isTwoFingered: Boolean,
                 var slothWeight: Int): Mammal(slothName)
data class Manatees(val manateeName: String): Mammal(manateeName)



fun Mammal.vertebraeCount(): Int{
    return when(this){
        is Sloths -> 10
        is Manatees -> 6
        else -> 7
    }
}
fun Mammal.knownSpeciesCount(): Int{
    return when(this){
        is Manatees -> 3
        is Panda -> 2
        is Sloths -> 6
    }
}
fun mammalFactCheck(mammal: Mammal, factCheck: KFunction1<Mammal, Int>): Int{
    return factCheck(mammal)
}


What I have tried:

I am really sorry for my "weak" questions that may not suit this community.
I do not understand this signature:
fun mammalFactCheck(mammal: Mammal, factCheck: KFunction1<Mammal, Int>): Int{
    return factCheck(mammal)

I know that in order to obtain function reference we use ::
Mammal::vertebraeCount
we get kind of: fun PackageName.Mammal.vertebraeCount(): kotlin.Int
And what does this call do:
crewCrewCrew.forEach {
    mammalFactCheck(it, Mammal::vertebraeCount)
    mammalFactCheck(it, Mammal::knownSpeciesCount)

}
Posted
Updated 8-Jul-21 23:51pm
v2

1 solution

I am not a kotlin expert, but ...
Kotlin
crewCrewCrew.forEach {
    mammalFactCheck(it, Mammal::vertebraeCount)
    mammalFactCheck(it, Mammal::knownSpeciesCount)
}

... appears to be a loop which iterates over the entries in the crewCrewCrew list (created above). For each entry it then calls mammalFactCheck, passing it (the mammal object from the forEach statement), and a check value. The mammalFactCheck function uses the mammal object and the two function pointers vertebraeCount and knownSpeciesCount, to get the relevant values for the type of mammal. But it does not do anything with those returned values.

If you run this code in your debugger and step through you will be able to see the sequence of operations.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900