Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type equality in Scala

Tags:

scala

Here is a little snippet of code:

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

Now, inside foo, how do I:
1) verify if B is the same type as A?
2) verify if B is a subtype of A?

like image 603
Sergey Weiss Avatar asked Jul 12 '12 11:07

Sergey Weiss


2 Answers

You need implicit type evidences, <:< for subtype check and =:= for same type check. See the answers for this question.

like image 104
xiefei Avatar answered Oct 14 '22 10:10

xiefei


As a side note, generalized type constraints aren't actually necessary:

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 way, because it both slightly improves type inference and guarantees that no extraneous runtime data is used.

like image 31
Ptharien's Flame Avatar answered Oct 14 '22 10:10

Ptharien's Flame