How to check true or false values in the list kotlin

Satheesh Guduri
2 min readDec 15, 2021

In this article I am going to share some knowledge, if you have a better idea than this please comment below. The question is we are going to check the student is passed or failed.

Suppose a student is having 4 subjects for that we are taking one Subject class.The Subject class contains subject name and the result like below.

class Subject(val name:String,val result:Boolean)

Suppose he failed in one subject it means the student is failed otherwise he is passed.

To store the subjects we will take the mutable list.

fun main() {
var list = mutableListOf<Subject>()
}

After this, we will add the subject objects with the name and result like below

fun main() {
var list = mutableListOf<Subject>()
list.add(Subject(“Maths”,true))
list.add(Subject(“Science”,true))
list.add(Subject(“Computers”,true))
list.add(Subject(“English”,false))
}

Now, we need to check whether the student is passed or failed, if he failed in one subject it means he failed.

fun main() {
var list = mutableListOf<Subject>()
list.add(Subject(“Maths”,true))
list.add(Subject(“Science”,true))
list.add(Subject(“Computers”,true))
list.add(Subject(“English”,false))

var isPassed = isStudentPassed(list)
if(isPassed)
println(“student — isPassed”)
else
println(“student — failed”)
}

Here, we are checking with this function isStudentPassed(list), this function returns true if student passed in all the subjects otherwise false

fun isStudentPassed(students : MutableList<Subject>) : Boolean{
students.forEach { student ->
if(!student.result)
return false
}
return true

}

In the above code, we are checking each subject with the result if one subject result is failed then it returns false and not checking for other subjects or the result is true.

Output: student — failed

Another way:

Instead of for each, we can get the result like below

fun isStudentPassed(students : MutableList<Subject>) : Boolean{
return students.none { student->!student.result}
}

As @mkrussel77 he said, we can use all function instead of none like below.

fun isStudentPassed(students : MutableList<Subject>) : Boolean{
return students.all { student->student.result}
}

Output: student — failed

Thanks for reading this article, if you like it please clap for me and suggestions please comment.

--

--