zoukankan      html  css  js  c++  java
  • Scala 学*笔记(二)— Everything is an object

    Everything is an object

    前言

    Scala is a pure object-oriented language in the sense that everything is an object,including numbers or functions. It differs from Java in that respect, since Java distinguishes primitive types (such as boolean and int) from reference types, and does not enable one to manipulate functions as values.


    Numbers are objects
    Since numbers are objects, they also have methods.
    例如,算式 1 + 2*3 / x,若将每一个number都写成对象的方式,则为
    .+(((2).*(3))./(x))
    括号在式子中是必须的,因为如果写成1.+(2)的话,scala的词法分析器会这样断句:
    +    2
    如此一来,前面的“1.”就会被当成“1.0”,这样计算出来的结果就是double类型的数据了。例如:

    如果是按规范写成(1).+(2)的话,就还是int类型的数据

    之所以用这么矫情的写法,主要是为了说明number在scala中也是object,它拥有".+"方法。Scala也是可以用更贴**时*惯的算式写法的:


    Functions are objects
    对java程序员来说,更新鲜的一点就是function也是object。这以为着function也可以当成value一样进行传递。
    Functions are also objects in Scala.It is therefore possible to pass functions as arguments, to store them in variables, and to return them from other functions.
    对C语言还有印象的人应该还记得call-back function(回调函数)这个东西。它其实就相当于把函数当做值来传递了,不过在C中传递的是这个函数的地址。
    看看下面这段代码:

    object Timer {
        def oncePerSecond(callback: () => Unit) {
            while(true) { callback(); Thread sleep 1000 }
        }
        def timeFlies() {
            println("time flies like an arrow...")
        }
    
        def main(args: Array[String]) {
            oncePerSecond(timeFlies)
        }
    }

    可以看到,timeFlies函数被当做回调函数注册给了oncePerSecond。这种方式跟C很像。不过,这里面其实有点浪费,因为timeFlies函数其实根本不需要名字,因为它只在一个特定的地方用到了。如果把它想象成“一团东西”,那么只要把“这团东西”塞到它应该待的位置即可,根本不会再有别人关心它叫什么名字(好像有点伤感……)
    这样,就产生了anony-mous functions(匿名函数),如下:

    object TimerAnonymous {
        def oncePerSecond(callback: () => Unit) {
            while(true) { callback(); Thread sleep 1000 }
        }
        def main(args: Array[String]) {
            oncePerSecond(() => println("time flies like an arrow..."))
        }
    }

    可以看到() =>println("time flies like an arrow...")这团东西”(其实是一个匿名函数)被当做一个object,直接塞到了使用它的地方。这个做法跟javascript的匿名函数很像,但是无论在有C中还是java中都是挺难想象的。Scala就可以这么做。

    总结:
    Scala在java的基础之上,将面向对象的“万物皆为对象”的思想更推进了一步,把function也视为object,允许它作为参数出现,也允许它被赋值给一个变量,甚至还运行它作为一个返回值来进行回馈。

  • 相关阅读:
    记一次bash脚本报错原因
    说说JSON和JSONP,也许你会豁然开朗,含jQuery用例(转载)
    python 正则空格xa0实录 与xpath取 div 里面的含多个标签的所有文字
    python3的时间日期处理
    easyui的 一些经验
    hash是什么?
    vue.js 入门
    python __nonzero__方法
    Jmeter之『并发』
    Docker之网络篇
  • 原文地址:https://www.cnblogs.com/elaron/p/2866683.html
Copyright © 2011-2022 走看看