加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala:理解参数多态性

发布时间:2020-12-16 18:20:23 所属栏目:安全 来源:网络整理
导读:有什么区别 def drop1[A](l: List[A]) = l.tail 和 def drop1(l: List[Int]) = l.tail 如果用法看起来像 drop1(List(1,2,3)) ? 应该何时使用其中一个,为什么?虽然我能理解第二个例子,但我并不真正理解第一个例子的目的. 解决方法 真的很简单.你的第一个例
有什么区别

def drop1[A](l: List[A]) = l.tail

def drop1(l: List[Int]) = l.tail

如果用法看起来像

drop1(List(1,2,3))

应该何时使用其中一个,为什么?虽然我能理解第二个例子,但我并不真正理解第一个例子的目的.

解决方法

真的很简单.你的第一个例子是指泛型的概念.

泛型有一个简单的目标,使某些方法通用,例如非类型依赖.

让我们看看这个简单的例子.假设我想为List编写drop1方法.

我可以为每种类型写一个:(慢,重复):

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.

基本上说:无论List中包含什么类型,给我尾巴.
而不是为几乎无限数量的类型编写成千上万的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,3).drop1

重命名众所周知的库方法通常也是一个坏主意.尾部操作不安全,跌落是安全的.所有你造成的都是混乱,因为有一个默认的drop方法.

List(1,3) drop 1

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读