Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking the array size and list size inside a when statement in Kotlin

Tags:

java

kotlin

I am new to Kotlin and programming in general. I really like the idea of pattern matching and as you can see at the code below, I was experimenting with the when statement.

fun main(args: Array<String>) {


    val myAr = arrayOf(1,2,3)
    val myL = listOf(1,2,3)

    fun probablyBlind() {

       when(myL.size != myAr.size) {

          myL.size > myAr.size -> {
            println("myL.size > myAr.size = ${myL.size > myAr.size}")
          }
          myL.size < myAr.size -> myAr.forEach { println(it) }
      }

      if(myL.size != myAr.size) {
        println("Inside if. myL.size > myAr.size = 
        ${myL.size > myAr.size}")
      }
   }

   probablyBlind()
 }

If you run the code the result is :

myL.size > myAr.size = false

So that means that at some point the size of the list is different from the size of the array. Then it evaluates to true the first comparison inside the when statement. But then it prints out false. Which means it shouldn't run this part of the code. The if statement never evaluates to true.

Can anyone help me with this please? Maybe it's something really easy that I can't see at the moment. If that's the case, excuse me.

like image 271
Vdav Avatar asked Feb 12 '18 18:02

Vdav


People also ask

How do I find the size of an array in Kotlin?

To get size of Array in Kotlin, read the size property of this Array object. size property returns number of elements in this Array. We can also use count() function of the Array class to get the size.

How do I find the length of a string array in Kotlin?

To find the length of string in Kotlin language, you can use String. length property. String. length property returns the number of characters in the string.

What is the difference between list and array in Kotlin?

The major difference from usage side is that Arrays have a fixed size while (Mutable)List can adjust their size dynamically. Moreover Array is mutable whereas List is not. Furthermore kotlin. collections.

How does Kotlin check element in list?

To check if a specific element is present in this List, call contains() function on this List object and pass given element as argument to this function. The Kotlin List. contains() function checks if the list contains specified element and returns a boolean value.


2 Answers

when(myL.size != myAr.size)

Here you specifed that the when-expression is a Boolean value, the result of comparing MyL.size and myAr.size. Let's say they are equal, this means you search for a match of the value false.

myL.size > myAr.size -- your first when-clause. Since the sizes are equal, this evaluates to false and matches the when-expression.

What you actually wanted to say was just

when {
    myL.size > myAr.size -> {
        println("myL.size > myAr.size = ${myL.size > myAr.size}")
      }
    myL.size < myAr.size -> myAr.forEach { println(it) }
}
like image 126
Marko Topolnik Avatar answered Oct 10 '22 17:10

Marko Topolnik


The following is just a little showcase of another possibility, which might make sense in more complex scenarios.

You could wrap the comparison result into a few objects which let the when clause look nicely as follows:

fun probablyBlind() {
    when (ComparisonResult.of(myAr.size, myL.size)) {
        Equal -> {
            println("equally sized")
        }
        RightGreater -> println("myL.size > myAr.size = ${myL.size > myAr.size}")
        LeftGreater -> myAr.forEach { println(it) }
    }
}

To get it working simply create the following wrappers:

sealed class ComparisonResult {
    companion object {
        fun of(t1: Int, t2: Int): ComparisonResult = when {
            t1 == t2 -> Equal
            t1 > t2 -> LeftGreater
            t1 < t2 -> RightGreater
            else -> throw IllegalStateException()
        }
    }
}

object Equal : ComparisonResult()
object LeftGreater : ComparisonResult()
object RightGreater : ComparisonResult()
like image 44
s1m0nw1 Avatar answered Oct 10 '22 19:10

s1m0nw1