如何使用不能为Any的param类型定义scala方法 [英] How to define a scala method with type param that cannot be Any
问题描述
在下面的示例中,我想定义一个contains
方法,如果a
和b
不是相同的基本类型,则该方法不会编译.
In below example, I want to define a contains
method that doesn't compile if a
and b
are not of the same base type.
- 在
contains1
impl中,如果a
是Seq[Int]
并且b是String
,则将T
派生为Any
并进行编译.这不是我想要的. - 在
contains2
impl中,如果a
是Seq[Int]
并且b是String
,则它不会编译.行为就是我想要的.
- In
contains1
impl, ifa
isSeq[Int]
and b isString
,T
is derived to beAny
, and it compiles. This is not I want. - In
contains2
impl, ifa
isSeq[Int]
and b isString
, then it doesn't compile. The behavior is what I want.
def contains1[T](a: Seq[T], b: T): Boolean = a.contains(b)
println(contains1(Seq(1,2,3), "four")) // false
def contains2[T: Ordering](a: Seq[T], b: T): Boolean = a.contains(b)
println(contains2(Seq(1,2,3), "four")) // compilation error
// cmd7.sc:1: No implicit Ordering defined for Any.
// val res7 = isMatched(Seq(1,2,3), "s")
^
// Compilation Failed
但是,是否有一种更简单的方法来实现与contains2
中相同的行为? Ordering
上下文绑定使我感到困惑,因为该方法与排序/排序完全无关.
However, is there a simpler way to achieve the same behaviour as in contains2
? Ordering
context bound confuses me as the method has nothing to do with sorting/ordering at all.
推荐答案
您可以使用通用类型约束运算符=:=
.
例如:
def contains[A,B](a: Seq[A], b: B)(implicit evidence: A =:= B): Boolean = a.contains(b)
然后:
println(contains1(Seq(1,2,3), "four")) //fails with Cannot prove that Int =:= String.
println(contains1(Seq("one"), "four")) //returns false
println(contains1(Seq("one", "four"), "four")) //true
有关广义类型约束的更多信息此处.
More on generalized type constraints here and here.
正如LuisMiguelMejíaSuárez所注意到的,您也可以考虑使用B <:< A
而不是A =:= B
.我不会详细说明这两者之间的区别,因为在链接的答案和文章中对此进行了描述,但是总而言之,<:<
还将允许作为A
子类型的所有B
,而=:=
需要匹配的类型完全是
As LuisMiguelMejíaSuárez noticed, you could also consider using B <:< A
instead of A =:= B
. I won't elaborate on differences between these two because it's described in linked answer and article, but in brief, <:<
would also allow all B
that are a subtype of A
, while =:=
needs types to match exactly.
这篇关于如何使用不能为Any的param类型定义scala方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!