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

scala – 是一种方法还是类?

发布时间:2020-12-16 21:31:52 所属栏目:安全 来源:网络整理
导读:他在书中写道: Class ::,pronounced “cons” for “construct,” represents non-empty lists. 和 The list construction methods :: and ::: are special. Because they end in a colon,they are bound to their right operand. That is,an operation suc
他在书中写道:

Class ::,pronounced “cons” for “construct,” represents non-empty lists.

The list construction methods :: and ::: are special. Because they end
in a colon,they are bound to their right operand. That is,an
operation such as x :: xs is treated as the method call xs.::(x),not
x.::(xs). In fact,x.::(xs) would not make sense,as x is of the list
element type,which can be arbitrary,so we cannot assume that this
type would have a :: method. For this reason,the :: method should
take an element value and yield a new list

那么::一个方法还是一个类?

解决方法

它都是 class和 method.缺点是类型参数类.列表[A]有两个子类:缺点和零.由于Cons是一个类,它可以由其构造函数创建,如下所示:

val s = new ::[Int](4,Nil)

缺点是一个case类,当我们进行模式匹配时,我们使用构造函数.缺点也是在其两个子类中实现的列表类的方法.因此,我们可以在上面创建的cons类中使用cons方法.

val s1 = s.::(5)

部分混淆可能会出现,因为我们通常使用List对象的apply方法创建列表:

val s2 = List(1,2,3)

通常,对象的apply方法返回与对象具有相同名称的类的新实例.但这只是惯例.在这种特殊情况下,List对象返回一个新的Cons子类实例. List类本身是一个封闭的抽象类,所以不能被实例化.所以上面的应用方法如下:

val s2 = 1 :: 2 :: 3 :: Nil

以“:”结尾的任何方法都是操作数右侧的方法,因此可以将其重写为

val s2 = 1 :: (2 :: (3 :: Nil)) //or as
val s2 = Nil.::(3).::(2).::(1)

因此,Nil对象上的Cons(:)方法将3作为参数,并生成Cons类的匿名实例化,其中3为头,对Nil对象的引用为尾.让我们称这个匿名对象c1.然后在c1上调用Cons方法,以2为参数,返回一个新的匿名缺省实例化称为c2,它的头为2,对c1为尾.然后最后,c2对象的cons方法以1为参数,返回名为“1”的命名对象s2作为其头,引用c2作为尾.

第二个困惑之处在于REPL和Scala工作表使用一个类’toString方法来显示结果.所以工作表给了我们:

val s3 = List(5,6,7)     // s3  : List[Int] = List(5,7)
val s4 = List()            // s4  : List[Nothing] = List()
val s5: List[Int] = List() // s5  : List[Int] = List()
s3.getClass.getName        // res3: String = scala.collection.immutable.$colon$colon
s4.getClass.getName        // res4: String = scala.collection.immutable.Nil$
s5.getClass.getName        // res5: String = scala.collection.immutable.Nil$

如上所述,List是密封的,所以新的子子类不能被创建为Nil是一个对象,而Cons是final.由于Nil是一个对象,它不能被参数化. Nil继承自List [Nothing].乍一看,听起来不那么有用,但记住这些数据结构是不可变的,所以我们永远不能直接添加到它们中,而Nothing是每个其他类的子类.所以我们可以将Nil类(间接)添加到任何列表中,没有任何问题.缺点类有两个成员头和另一个列表.它是一个相当整洁的解决方案,当你时钟.

我不知道这是否有实际用途,但您可以使用Cons作为一种类型:

var list: ::[Int] = List (1,3).asInstanceOf[::[Int]]
println("Initialised List")
val list1 = Nil
list = list1.asInstanceOf[::[Int]] //this will throw a java class cast exception at run time
println("Reset List")

(编辑:李大同)

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

    推荐文章
      热点阅读