Scala list contains vs array contains

Of interest, why does this work in Scala:

val exceptions = List[Char]('+') assertTrue(exceptions.contains('+')) 

But it is not

 val exceptions = new Array[Char]('+') assertTrue(exceptions.contains('+')) 
+6
source share
2 answers

Because you wrote a new ArrayChar. The argument is the size of the array, and "+", unfortunately, is converted to int to give the size. And the returned array is filled with Char (0).

You should just do Array[Char]('+') , '+' then will be the only element in the array.

+8
source

Try in REPL, which makes the answer obvious:

 scala> val exceptions = new Array[Char]('+') exceptions: Array[Char] = Array( , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ) 

+ has promotion char -to-int.

 scala> val exceptions = Array[Char]('+') exceptions: Array[Char] = Array(+) scala> exceptions.contains('+') res3: Boolean = true 

is the equivalent of a List case.

+7
source

Source: https://habr.com/ru/post/922263/


All Articles