Java Array vs Scala Array

It seems that one difference between a Java array and a Scala Array is a Java array. Scala Array no. Both are mutable. In java, the sorting method can accept different arrays, such as String or Int arrays. This is often cited as a good example of the Liskov replacement principle. Sounds like a good design to me? At Scala, we know that Array is not a co-option. Although Scala Array is designed later than Java. I do not see how Scala Array is better in the aspect of co-dispersion. Generally speaking, it is better than Java.

+4
source share
1 answer

When you look further, you will find that the fathers of the Java language later decided to create no Generics covariance . And this is for good reason.

Because it is List<Apple>not List<Fruit>. Otherwise, you could do something like

List<Apple> apples = new ArrayList<>();
List<Fruit> fruits = apples;
fruits.add(new Banana());

but don't you expect that

Apple badApple = apples.get(0);

- safe call? If you allow covariance here, it is not!

And with surprise: what a problem in Java arrays!

Therefore it is really a problem that Java arrays are covariant! And it's better that Scala arrays actually allow you to precisely control your β€œvariance”. In Scala, you have full control over dispersion; whereas in Java they are always covariant.

"" , sort(Object[] objects) , - Java. 20 . "" , : -.

"" , Java ArrayStoreException. , Java- !

+10

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


All Articles