Scala 模式匹配类型错误

Scala 模式匹配类型错误,scala,intellij-idea,Scala,Intellij Idea,下面是IntelijIDEA中的map1.scala文件 看来我又撞到墙上了。我不知道为什么会出现以下错误: abstract class List[T] { def map[U](f: T => U): List[U] = { this match { case Nil => this case x :: xs => ??? } } } 案例Nil:模式类型与预期类型不兼容:找到Nil.type预期列表[T] 此

下面是IntelijIDEA中的map1.scala文件

看来我又撞到墙上了。我不知道为什么会出现以下错误:

abstract class List[T] {
   def map[U](f: T => U): List[U] = {
     this match {
       case Nil => this
       case x :: xs => ???
     }
   }
 }
案例Nil:模式类型与预期类型不兼容:找到Nil.type预期列表[T] 此:类型列表[T]的表达式不符合预期的类型列表[U] 发现x::xs模式类型不兼容::B必需列表[T]


我什么都试过了。。。但还是有这个问题。不过知道请回复

实际上,您的代码存在一些问题:

  • 列表的不变类型参数T
  • 不存在对象零
  • 缺席操作员::
  • 缺少对象::具有unapply函数
试试这个:

abstract class List[+A]
  def head: A
  def tail: List[A]

  def map[B](f: A => B): List[B] = 
    if (this == Nil) Nil 
    else new ::(f(head), tail map f)
}

case object Nil extends List[Nothing] {
  def head = ??? // not interested in throwing more appropriate exception
  def tail = ???
} 

case class ::[T](head: T, tail: List[T]) extends List[T]
那你就可以用了

(1 :: 2 :: 3 :: Nil).map(_.toString)

实际上,您的代码存在一些问题:

  • 列表的不变类型参数T
  • 不存在对象零
  • 缺席操作员::
  • 缺少对象::具有unapply函数
试试这个:

abstract class List[+A]
  def head: A
  def tail: List[A]

  def map[B](f: A => B): List[B] = 
    if (this == Nil) Nil 
    else new ::(f(head), tail map f)
}

case object Nil extends List[Nothing] {
  def head = ??? // not interested in throwing more appropriate exception
  def tail = ???
} 

case class ::[T](head: T, tail: List[T]) extends List[T]
那你就可以用了

(1 :: 2 :: 3 :: Nil).map(_.toString)

Nil
是标准库中的
List
类型,您可以将其与自己的类
List进行比较。
将列表重命名为
MyList
MyNil
不要混淆自己。
Nil
是标准库中的一种
List
,您可以将其与自己的类
列表进行比较。
将列表重命名为
MyList
MyNil
不要混淆自己。在类
:[T]的情况下,可能需要扩展
List[T]
@Dmitry,在我按照你说的做了之后,它一直在(如果this==Nil)Nil[类型为Nil.type的表达式不符合预期的类型列表[B].@Spartan我忘了做::扩展列表[t]。对不起,也许你需要在case class
::[T]
@Dmitry中扩展
List[T]
,在我按照你说的做了之后,它一直在(如果this==Nil)Nil[类型Nil.type的表达式不符合预期的类型List[B]@Spartan我忘了做::扩展List[T]中给我一个错误。很抱歉