Equality Type in Scala

Here is a small piece of code:

class Foo[A] { def foo[B](param: SomeClass[B]) { // } } 

Now, inside foo , like me:
1) check if B is the same type as A?
2) check if B is a subtype of A?

+6
source share
3 answers

You need implicit type confirmations, <:< for checking a subtype, and =:= for checking the same type. See the answers to this question .

+7
source

1) check if B is the same type as A

 class Foo[A] { def foo(param: SomeClass[A]) = ??? } // or class Foo[A] { def foo[B](param: SomeClass[B])(implicit ev: A =:= B) = ??? } 

2) check if B is a subtype of A?

 class Foo[A] { def foo[B <: A](param: SomeClass[B]) = ??? } // or class Foo[A] { def foo[B](param: SomeClass[B])(implicit ev: B <:< A) = ??? } 

In your case, you do not need restrictions of a generalized type (i.e. =:= , <:< ). They are needed when you need to add a constraint on a type parameter that is defined elsewhere, and not on a method.

eg. To ensure A is String :

 class Foo[A] { def regularMethod = ??? def stringSpecificMethod(implicit ev: A =:= String) = ??? } 

Here you cannot enforce a type constraint without a generic type constraint.

+6
source

As a side note, generalized type constraints are not actually needed:

 class Foo[A] { def foo_subParam[B <: A](param: SomeClass[B]) {...} def foo_supParam[B >: A](param: SomeClass[B]) {...} def foo_eqParam[B >: A <: A](param: SomeClass[B]) {...} def foo_subMyType[Dummy >: MyType <: A] {...} def foo_supMyType[Dummy >: A <: MyType] {...} def foo_eqMyType[Dummy1 >: MyType <: A, Dummy2 >: A <: MyType] {...} } 

In fact, I prefer this method because it somehow improves type inference and ensures that no external runtime data is used.

+6
source

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


All Articles