为什么 Scala List[Int].contains 接受 Option[Int]? [英] Why does Scala List[Int].contains accept Option[Int]?

查看:37
本文介绍了为什么 Scala List[Int].contains 接受 Option[Int]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以给定列表:

val a:List[Int] = List(1,2,3)

你可以这样做:

a.contains(Option(2))

返回假.我从以下函数定义中了解到,完全允许编译是故意完成的:

Which returns false. I understand from the following function definitions that allowing this to compile at all was done on purpose:

def contains[A1 >: A](elem : A1) : scala.Boolean = {...}
sealed abstract class Option[+A]() ...

我不明白为什么 - 是否有一个有用的用例?如果它在比较之前自动展平了选项,因此上面的返回 true 那么它可能有用,但它总是返回 false.

What I don't understand is why - is there a use case where this is useful? If it automatically flattened the option before the comparison so the above returned true then it might be useful but as is it will always return false.

我这么问是因为很容易忘记解开传递给 List.contains 的 Option 变量,从而导致潜在的难以发现错误.

I ask because it's easy to forget to unwrap your Option variable that you pass to List.contains, leading to potentially difficult to find bugs.

谢谢!

推荐答案

想象以下内容:

sealed trait Result
case class SimpleResult(x: Int) extends Result
case class FancyResult(x: Int, y: Int) extends Result

val okResults: List[SimpleResult] = // ...

def calcResult: Result = ???

okResults.contains(calcResult)

在这种情况下,您可以使用 List 类型的超类型调用 contains.

This is a case where it is useful that you can call contains with a supertype of the type of the List.

在您的情况下,会发生令人讨厌的副作用:Option[Int] 不是 Int 的超类型.然而,它们有一个共同的超类型:Any.所以你对 contains 的调用被推断为:

In your case, a nasty side-effect happens: Option[Int] is not a supertype of Int. However, they have a common supertype: Any. So your call to contains gets inferred to:

a.contains[Any](Option(2))

由于Option[Int]Any 的子类型,您可以将其传递给contains.在大多数情况下,这可能是您不想要的,但很难(不可能?)在 Scala 的类型系统中定义这样的接口.

Since Option[Int] is a subtype of Any, you are allowed to pass it to contains. This is probably something you wouldn't want in most cases, but it is hard (impossible?) to define such an interface in Scala's type system.

这篇关于为什么 Scala List[Int].contains 接受 Option[Int]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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