为什么我不能运行这样的Scala代码? (reduceRightList类方法) [英] Why can't I run such scala code? (reduceRight List class method)

查看:64
本文介绍了为什么我不能运行这样的Scala代码? (reduceRightList类方法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

abstract class List[T] {
  def reduceRight(op: (T, T) => T): Either[String, T] = this match {
    case Nil => Left("reduce on empty list")
    case x => Right(x)
    case x::xs => Right(op(x, xs, reduceRight(op)))
  }
}

我的错误:

模式类型与预期类型不兼容,dound:Nil.type, 必填:列表[T]

我是Scala中的一名新手,所以,请描述您的答案.

解决方案

tldr:为您的类命名其他名称,让该方法接受第二个参数,即您要减少的List.

问题是您将您的类命名为List,该类已经是Scala中的类的名称.单独使用它实际上并不会破坏代码,但是对于您是指Scala List还是您的自定义List来说,这可能会引起一些困惑.

然后将其混淆,并尝试使用自定义类,就好像它是常规的Scala List.特别是要尝试对Nil::之类的东西使用模式匹配.这些仅适用于Scala List,不适用于您的自定义版本.当然,您也可以编写代码以使其与您的自定义List一起使用,但是您仍然需要小心以确保您也引用了哪一个,如果您采用这种方法,我建议您使用其他名称.

一个更简单的解决方案是为该类命名,然后更改减少权限以将常规List也用作参数.像这样:

abstract class MyClass {
  def reduceRight[T](list: List[T], op: (T, T) => T): Either[String, T] = list match {

My code:

abstract class List[T] {
  def reduceRight(op: (T, T) => T): Either[String, T] = this match {
    case Nil => Left("reduce on empty list")
    case x => Right(x)
    case x::xs => Right(op(x, xs, reduceRight(op)))
  }
}

My error:

pattern type is incompatible with expected type, dound: Nil.type, required: List[T]

I'm a complete newbie in Scala, so, please, describe your answer.

解决方案

tldr: name your class something else, have the method take in a second parameter which is the List you want to reduce.

The problem is you named your class List which is already the name of a class in Scala. This on it's own is actually not going to break the code, but it can cause some confusion on whether you mean the Scala List or your custom List.

You then confuse it and try to use your custom class as if it were a regular Scala List. in particular trying to use pattern matching with things like Nil and ::. Those only work for the Scala List, not your custom one. You could of course also write the code for those to work with your custom List, but you still need to be careful to make sure which one you are referring too, I would recommend using different names if you go this route.

An easier solution is to name the class something else, then change Reduce right to also take in a regular List as a parameter. Something like this:

abstract class MyClass {
  def reduceRight[T](list: List[T], op: (T, T) => T): Either[String, T] = list match {

这篇关于为什么我不能运行这样的Scala代码? (reduceRightList类方法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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