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

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)}}看看花儿冲破北疆漫漫寒冬,妖娆绽放;

Scala 学习笔记(二)— Everything is an object

相关文章:

你感兴趣的文章:

标签云: