在类型不匹配时失败的`Seq.contains`的替代方案是什么?

Pra*_*pal 5 scala type-safety

与此Scala类似:为什么Seq.contains包含Any参数,而不是序列类型的参数?

如果你这样做 Seq(1, 2, 3).contains("dasdas")

这将编译并始终返回false。是否有引发类型错误的替代方法?这似乎是一个主要的wtf,contains总是返回false并且非常容易在代码审查中遗漏。

Joa*_*oan 7

您可以启用-Xfatal-warnings-Ywarn-infer-any使其在类型不匹配时失败。
这同样适用于平等检查==

这是我build.sbt用来避免像您遇到的那样奇怪的Scala 的示例:

scalacOptions ++= Seq(
  "-deprecation",
  "-explaintypes",
  "-feature",
  "-language:higherKinds",
  "-unchecked",
  "-Xcheckinit",
  "-Xfatal-warnings",
  "-Xfuture",
  "-Xlint",
  "-Yno-adapted-args",
  "-Ypartial-unification",
  "-Ywarn-dead-code",
  "-Ywarn-inaccessible",
  "-Ywarn-infer-any",
  "-Ywarn-nullary-override",
  "-Ywarn-nullary-unit",
  "-Ywarn-numeric-widen",
  "-Ywarn-unused"
) ++ (
  if (scalaVersion.value.startsWith("2.11")) Seq.empty
  else Seq("-Ywarn-extra-implicit")
Run Code Online (Sandbox Code Playgroud)

罗布·诺里斯(Rob Norris)上有一篇很棒的文章:https :
//tpolecat.github.io/2017/04/25/scalac-flags.html

仅供参考:在Scala 3中,通用平等将被通用平等取代,以解决您的问题:http :
//dotty.epfl.ch/docs/reference/contextual/multiversal-equality.html


pra*_*upd 5

您可以编写扩展方法以仅接受定义的类型,

implicit class ListOps[A](list: List[A]) {
  def typeSafeContains(a: A) = list.contains(a)
}

List(1, 2, 3).typeSafeContains(1)
List(1, 2, 3).typeSafeContains("does not work") //type mismatch error;
Run Code Online (Sandbox Code Playgroud)

离题,但我检查haskell具有类型安全contains

Prelude> elem 1 [1,2,3]
True

Prelude> elem "should not work" [1,2,3]

<interactive>:6:25: error:
    • No instance for (Num [Char]) arising from the literal ‘1’
    • In the expression: 1
      In the second argument of ‘elem’, namely ‘[1, 2, 3]’
      In the expression: elem "should not work" [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)