如何使用不能为Any的param类型定义scala方法 [英] How to define a scala method with type param that cannot be Any

查看:165
本文介绍了如何使用不能为Any的param类型定义scala方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我想定义一个contains方法,如果ab不是相同的基本类型,则该方法不会编译.

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中,如果aSeq[Int]并且b是String,则将T派生为Any并进行编译.这不是我想要的.
  • contains2 impl中,如果aSeq[Int]并且b是String,则它不会编译.行为就是我想要的.
  • In contains1 impl, if a is Seq[Int] and b is String, T is derived to be Any, and it compiles. This is not I want.
  • In contains2 impl, if a is Seq[Int] and b is String, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆