(Co) Difference in lists other than stacks in Scala?

When I write this code, I have a compilation error in Scala

var s: Stack[_ <: Number] = new Stack[Integer]; 
s.push(new Integer(1)); //compile-error: type mismatch; found :Integer required: _$bqjyh where type _$bqjyh <: Number
s.push(null); //compile-error: type mismatch; found   : Null(null) required: _$2 where type _$2 <: Objects.Vehicle

This is equivalent to the covariant collection in Java because of the pattern; it's exact type is unknown, so we cannot add something to the stack.

But with lists, I will not get the same error:

   var list: List[_ <: Number] = Nil;
   var intList : List[Integer] = new Integer(1) :: Nil;
   list = intList ; //no error
   list = new Float(2) :: vehicles;  //even float allowed

Now I can add even float, but in fact I believe that listis listof Integers, therefore not allowed Floats.

1) Why is this allowed by lists and not using Stacks? Is this related to cons (: :) operator?

2) What is the type of list? Is it dynamic?

3) Why is this allowed in Scala and not in Java?

4) Is it possible to add something to the stack? ( nulldoesn't work, in Java this is because generic types only allow reference types)

+3
2

:: . , x :: xs List[ commonSupertypeOf[ typeOf[x], elementTypeOf[xs] ] ] ( scala, , ), xs. xs List[Float] x Integer, x :: xs List[Numeric], xs List[Float], .

add, , . xs.add(x) Integer a Stack, Stack<Float>, .

, x :: xs . , , typeckecks:

:: a List[A] : def :: [B >: A] (x: B) : List[B].

, A B, B A, :: B, A B. , someInteger :: someFloats, , B is Numeric A is Float, .

java-, <B supertypeOf A> List<B> prepend(B item), , supertypeOf java.

+6

Scala , . , . , , , ( Java- .)

+4

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


All Articles