这真的很简单。你的第一个例子涉及的概念generics.
Generics有一个简单的目标,制定一定的方法generic,例如不依赖于类型。
让我们看一下这个简单的例子。说我想写一个drop1
方法用于List
.
我可以为每种类型写一个:(缓慢,重复):
def drop1(l: List[Int]): List[Int] = l.tail // this only works for Int
def drop1(l: List[String]): List[String] = l.tail // this only works for String
您可以看到如何为每种类型编写上述内容。为了克服这个问题,你可以使用泛型:
def drop1[A](l: List[A]): List[A] = l.tail // this works for any given type.
这实质上是说:无论列表中包含的类型是什么,都给我尾巴。
而不是编写数千种变体drop1
对于几乎无限数量的类型,我只需要编写一种。
现在在 Scala 中,您的实现最好通过以下方式完成:
implicit class ListOps[A](val l: List[A]) extends AnyVal {
def drop1: List[A] = l match {
case head :: tail => tail
case Nil => Nil
}
}
// you can now have
List(1, 2, 3).drop1
重命名众所周知的库方法通常也是一个坏主意。 Atail
操作不安全且drop
是安全的。你造成的只是混乱,因为有一个默认值drop
method.
List(1, 2, 3) drop 1