Search code examples
kotlincontains

A way to detect default value not changed and cleaning up code . Kotlin


I have been coding in Kotlin for a few months now. I still have a lot to learn I know this. I have a piece of code that in my head should work. I am not happy with how it looks, and I feel it can be done in a better way.

Can someone please help show me the right way of doing what I am currently want to do.

 btnSend.setOnClickListener {
            var x =0

             var exceptionList = ArrayList(partsList.filter { (it.Exception) })

             exceptionList.forEach {
                 if(it.EReason.contains("Select a reason")){x=1}}

             if( x == 1 ){
                 val builder = AlertDialog.Builder(this)
                 builder.setMessage("Please select a reason for the current exception")
                 //    Toast.makeText(context,"Data capture canceled",Toast.LENGTH_LONG).show()
                 builder.setIcon(android.R.drawable.ic_dialog_alert)
                 builder.setNeutralButton("Cancel"){dialogInterface , which ->
                 }
                 val alertDialog: AlertDialog = builder.create()

                 alertDialog.setCancelable(true)
                 alertDialog.show()

             }else{ ...

The aim of the code is to look trough my arraylist and find out if one of the fields exceptionlist[x].EReason still contains the default value and has not been changed. The field is populated by a spinner inside my Recylerview. it.Exception is a checkbox that filters my array to only the selected items.


Solution

  • You can probably rewrite this part:

    var x =0
    
    var exceptionList = ArrayList(partsList.filter { (it.Exception) })
    
    exceptionList.forEach {
        if(it.EReason.contains("Select a reason")){x=1}}
    if( x == 1 ){
    

    as:

    if (partsList.any { it.Exception && it.EReason.contains("Select a reason") })