scala初探

来源:互联网 发布:mac ox版本升级mac os 编辑:程序博客网 时间:2024/05/27 12:21

最近scala随着spark的发展在市场中挂起了一阵火热的风暴,那么scala到底怎么样呢,让我们一探究竟吧

One of Scala’s strengths is that it makes it very easy to interactwith Java code. All classes from thejava.lang package areimported by default, while others need to be imported explicitly.

在官方文档中有着这样的一段话,上文的大概意思就是,scala最大的优势就是能和java代码互相调用,无需导入其他的包或者类库。

那么具体是怎么一回事呢,让我们看下面官方给出的示例代码.

    import java.util.{Date, Locale}    import java.text.DateFormat    import java.text.DateFormat._    object FrenchDate {      def main(args: Array[String]) {        val now = new Date        val df = getDateInstance(LONG, Locale.FRANCE)        println(df format now)      }    }

在如上的代码中,Date和DateFormat都是jdk的官方类库,scala无需重新编写该方法类库逻辑,只需要导入相应类库,即可进行逻辑处理的调用

Everything is an Object

在scala的官方文档中有这么一段大大的标题,一切皆对象。

Numbers are objects、

原谅小弟英文不好,理解能力也差,这块实在是没看懂,就看官方那么句话

Since numbers are objects, they also have methods. And in fact, anarithmetic expression like the following:

  1. 1 + 2 * 3 / x

consists exclusively of method calls, because it is equivalent to thefollowing expression, as we saw in the previous section:

  1. (1).+(((2).*(3))./(x))

Functions are objects

个人觉得scala最nx的地方就是把方法也看成对象,真正达到了一切皆对象的境界,让我们一起感受下面这段代码带给你的无穷魅力吧

package scalaimport java.util.Dateimport java.util.Localeimport java.text.DateFormatimport java.text.DateFormat._object ThreadPrint {  /**   * 这里需要传入一个回调方法   */  def Timer(callback: () =>Unit){    while(true){    // 循环调用该方法      callback()      Thread.sleep(500);    }  }  /**   * 定义一个业务方法   */  def service(){    val date = new Date    val sf = getDateInstance(LONG,Locale.CHINESE);    println("当前系统时间:" + sf.format(date));    val javaDate:Date = new Date();    println("当前系统秒数:" +     javaDate.getSeconds());  }    def main(args: Array[String]) {    // 讲回调方法作为一个参数对象传入  Timer(service);}}


Anonymous functions

  1. object TimerAnonymous {
  2. def oncePerSecond(callback: () => Unit) {
  3. while (true) { callback(); Thread sleep 1000 }
  4. }
  5. def main(args: Array[String]) {
  6. oncePerSecond(() =>
  7. println("time flies like an arrow..."))
  8. }
  9. }

将回调函数对象直接编写传入执行。只不过风格不太好,一般的情况下(除非极特殊的业务需求),不会以这样不利于维护的风格进行编程
1 0