Type equality in Scala

前端 未结 3 1303
抹茶落季
抹茶落季 2020-12-20 15:49

Here is a little snippet of code:

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

Now, inside foo, how do I:

3条回答
  •  误落风尘
    2020-12-20 16:50

    1) verify 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) verify 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 generalized type constraints (i.e. =:=, <:<). They're required when you need to add a constraint on the type parameter that is defined elsewhere, not on the method.

    e.g. To ensure A is a String:

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

    Here you cannot enforce the type constraint without a generalized type constraint.

提交回复
热议问题