【问题标题】:scala : <console>:28: error: type mismatch;scala:<控制台>:28:错误:类型不匹配;
【发布时间】:2021-11-05 11:16:15
【问题描述】:

我真的是语言 scala 的新手 我遇到的错误肯定和让你笑的一样简单


scala> sealed trait List[+A]
defined trait List

scala> case object Nil extends List[Nothing]
defined object Nil

scala> case class Cons[+A] (head: A, tail: List[A]) extends List[A]
defined class Cons

scala>

scala> def sum(ints: List[Int]): Int = ints match {
     | case Nil => 0
     | case Cons(x,xs) => x + sum(xs)
     | }
<console>:28: warning: match may not be exhaustive.
It would fail on the following inputs: Cons(_, _), Nil
       def sum(ints: List[Int]): Int = ints match {
                                       ^
sum: (ints: List[Int])Int

scala>

scala>

scala> def test(ints: List[Int]): Int = ints match {
     | case Cons(x, Cons(2, Cons(4, _))) => x
     | case Nil => 42
     | case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y
     | case Cons(h, t) => h + sum(t)
     | case _ => 101
     | }
test: (ints: List[Int])Int

scala>

scala>

scala> val example3 = List(1,2,3,4,5)
example3: List[Int] = List(1, 2, 3, 4, 5)

scala>

scala>

scala> test(example3)
<console>:28: error: type mismatch;
 found   : scala.collection.immutable.scala.collection.immutable.List[Int]
 required: List(in class $iw)[Int]
       test(example3)
            ^

我只想知道为什么类型不匹配? def 函数测试的输出很好 --> test: (ints: List[Int])Int! 非常感谢您的回复,

【问题讨论】:

  • List(1, 2, ...) 正在创建标准库List 的实例,而不是您自己定义的List,这就是问题所在。首先,我建议将其重命名为MyList (和MyNil & MyCons 以避免将来出现此类问题,其次,您需要实现自己的@987654328 @ 所以您可以使用该语法或将您的列表创建为MyCons(1, MyCons(2, MyNil))

标签: list scala function pattern-matching typeerror


【解决方案1】:

这是 Scala 控制台的问题。单独的输入不被视为同一文件的一部分。

因此,仅需要在同一个文件中的内容实际上并不能作为单独的输入。

sealed关键字还指定所有子类必须在同一个文件中。

所以,当你这样做时,

scala> sealed trait List[+A]
trait List

scala> case object Nil extends List[Nothing]
object Nil

scala> case class Cons[+A] (head: A, tail: List[A]) extends List[A]
class Cons

因为您在单独的输入中使用NilCons 扩展sealed trait,所以您的继承链实际上存在问题(Scala 控制台不会指出,但继承不会按预期工作)。

您需要提供“相同文件”代码作为单个输入。您可以为此使用:paste 模式。完成输入后,按ctrl-D 完成输入。

scala> :paste
// Entering paste mode (ctrl-D to finish)

sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A] (head: A, tail: List[A]) extends List[A]

// Exiting paste mode, now interpreting.

trait List
object Nil
class Cons

现在,您的sealed trait 将被NilCons 正确继承。而且您的sum 方法不会有任何问题。

scala> def sum(ints: List[Int]): Int = ints match {
     |   case Nil => 0
     |   case Cons(x,xs) => x + sum(xs)
     | }
def sum(ints: List[Int]): Int

同样companion 对象到classcase classs 也需要在同一输入中创建(使用:paste 模式)。

Scala 控制台(以及 IntelliJ 中的 Scala 工作表,以及 Ammonite 脚本)有很多隐藏的“特殊”东西,不应该用来学习 Scala。

我会建议你学习适当的 Scala sbt 项目和.scala 文件。

【讨论】:

  • 非常感谢 :paste 模式,我很好用!正如你所建议的那样,我更欣赏模式 .scala ;-)
猜你喜欢
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多