`
lobin
  • 浏览: 425516 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Scala

 
阅读更多
写道

 

写道

 

语法

Expr1 ::= ‘for’ (‘(’ Enumerators ‘)’ | ‘{’ Enumerators ‘}’) 

                     {nl} [‘yield’] Expr 

 

Enumerators ::= Generator {semi Generator} 

 

Generator ::= Pattern1 ‘<-’ Expr {[semi] Guard | semi Pattern1 ‘=’ Expr} 

 

Guard ::= ‘if’ PostfixExpr

 

 

 

例子

ForTest.scala

object ForTest extends App {

    var begin: Int = 1;

    var end : Int = 10;

    for (i <- begin until end) 

        println(i);

}

编译

>scalac -d classes ForTest.scala

执行

>scala ForTest

1

2

3

4

5

6

7

8

9

 

 

例子

ForTest2.scala

object ForTest2 extends App {

    var begin: Int = 1;

    var end : Int = 10;

    for {i <- begin until end

         j <- 1 until i}

        println("(" + i + "," + j + ")");

}

编译

>scalac -d classes ForTest2.scala

执行

>scala ForTest2

(2,1)

(3,1)

(3,2)

(4,1)

(4,2)

(4,3)

(5,1)

(5,2)

(5,3)

(5,4)

(6,1)

(6,2)

(6,3)

(6,4)

(6,5)

(7,1)

(7,2)

(7,3)

(7,4)

(7,5)

(7,6)

(8,1)

(8,2)

(8,3)

(8,4)

(8,5)

(8,6)

(8,7)

(9,1)

(9,2)

(9,3)

(9,4)

(9,5)

(9,6)

(9,7)

(9,8)

 

 

 

 

 

 

 

 

 

例子

ForTest3.scala

object ForTest3 extends App {

    var matrix = Array(1, 2, 3, 4, 5)

    for (i <- matrix)

        println(i);

}

编译

>scalac -d classes ForTest3.scala

执行

>scala ForTest3

1

2

3

4

5

 

 

 

 

 

 

 

 

 

 

例子

ForTest4.scala

object ForTest4 extends App {

    var matrix = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    for (i <- matrix

         if i % 2 == 0)

        println(i);

}

编译

>scalac -d classes ForTest4.scala

执行

>scala ForTest4

2

4

6

8

10

 

scala currying

object CurryingTest {

  def summary() {
  	println("---summary start---")
  	println("--- summary end ---")
  }
  
  def details() {
    println("---start usage start---")
  	println("--- start usage end ---")
  	
  	println("---restart usage start---")
  	println("--- restart usage end ---")
  	
  	println("---stop usage start---")
  	println("--- stop usage end ---")
  	
  	println("---status usage start---")
  	println("--- status usage end ---")
  }
  
  def usage[T](summary: => T)(details: => T): Unit = {
    println("---usage start---")
    summary
    println("-----------------")
    
    details
    println("--- usage end ---")
  }

  def main(args: Array[String]) {
  	usage(summary())(details())
  }
}


>scalac -d classes  CurryingTest.scala

>scala CurryingTest

---usage start---
---summary start---
--- summary end ---
-----------------
---start usage start---
--- start usage end ---
---restart usage start---
--- restart usage end ---
---stop usage start---
--- stop usage end ---
---status usage start---
--- status usage end ---
--- usage end ---

 

object CurryingTest {

  def summary() {
  	println("---summary start---")
  	println("--- summary end ---")
  }
  
  def details() {
    println("---start usage start---")
  	println("--- start usage end ---")
  	
  	println("---restart usage start---")
  	println("--- restart usage end ---")
  	
  	println("---stop usage start---")
  	println("--- stop usage end ---")
  	
  	println("---status usage start---")
  	println("--- status usage end ---")
  }
  
  def usage[T](summary: => T)(details: => T): Unit = {
    println("---usage start---")
    summary
    println("-----------------")
    
    
    details
    println("--- usage end ---")
  }

  def main(args: Array[String]) {
  	usage(summary())(details())
  	println("=================")
  	
  	usage(summary()) {
      println("===start usage start===")
  	  println("=== start usage end ===")
  	
  	  println("===restart usage start===")
  	  println("=== restart usage end ===")
  	
  	  println("===stop usage start===")
  	  println("=== stop usage end ===")
  	
  	  println("===status usage start===")
  	  println("=== status usage end ===")
    }
  }
}



>scalac -d classes  CurryingTest.scala

>scala CurryingTest

---usage start---
---summary start---
--- summary end ---
-----------------
---start usage start---
--- start usage end ---
---restart usage start---
--- restart usage end ---
---stop usage start---
--- stop usage end ---
---status usage start---
--- status usage end ---
--- usage end ---
=================
---usage start---
---summary start---
--- summary end ---
-----------------
===start usage start===
=== start usage end ===
===restart usage start===
=== restart usage end ===
===stop usage start===
=== stop usage end ===
===status usage start===
=== status usage end ===
--- usage end ---

scala currying-例子3

def swallow(log: (Object, Throwable) => Unit, action: => Unit) {
  try {
    action
  } catch {
    case e: Throwable => log(e.getMessage(), e)
  }
}

 

 

scala break

import org.junit.{Before, BeforeClass, Test}
import org.scalatest.junit.JUnitSuite

import scala.util.control.{Breaks, ControlThrowable}

private class BreakControl extends ControlThrowable

object ScalaBreaksTest {
  @BeforeClass
  def _init : Unit = {

  }
}

class ScalaBreaksTest extends JUnitSuite {

  private val breakException = new BreakControl

  def init : Unit = ScalaBreaksTest._init

  @Before
  def inittest() : Unit = {}

  @Test
  def test1() : Unit = {
    var i: Int = 0
    try {
      while (i < 100) {
        i = i + 1
        if (i == 5) {
          throw breakException
        }
      }
    } catch {
      case ex: BreakControl =>
        if (ex ne breakException) throw ex
    }
    println(i)
    assert (5 == i, "i must eq 5")
  }

  @Test
  def test2() : Unit = {
    val loop = new Breaks

    var i: Int = 0
    loop.breakable {
      while (i < 100) {
        i = i + 1
        if (i == 5) {
          loop.break
        }
      }
    }
    println(i)
    assert (5 == i, "i must eq 5")
  }
}

 

class TestClass(var arg1: Int, var arg2: Int) {
  
  def init() = {
    arg1 = 0;
    arg2 = 2;
  }
}

>scalac TestClass.scala

 

>javap -c TestClass

Compiled from "TestClass.scala"

public class TestClass {

  public int arg1();

    Code:

       0: aload_0

       1: getfield      #14                 // Field arg1:I

       4: ireturn

 

  public void arg1_$eq(int);

    Code:

       0: aload_0

       1: iload_1

       2: putfield      #14                 // Field arg1:I

       5: return

 

  public int arg2();

    Code:

       0: aload_0

       1: getfield      #21                 // Field arg2:I

       4: ireturn

 

  public void arg2_$eq(int);

    Code:

       0: aload_0

       1: iload_1

       2: putfield      #21                 // Field arg2:I

       5: return

 

  public void init();

    Code:

       0: aload_0

       1: iconst_0

       2: invokevirtual #26                 // Method arg1_$eq:(I)V

       5: aload_0

       6: iconst_2

       7: invokevirtual #28                 // Method arg2_$eq:(I)V

      10: return

 

  public TestClass(int, int);

    Code:

       0: aload_0

       1: iload_1

       2: putfield      #14                 // Field arg1:I

       5: aload_0

       6: iload_2

       7: putfield      #21                 // Field arg2:I

      10: aload_0

      11: invokespecial #32                 // Method java/lang/Object."<init>":()V

      14: return

}

 

object Test {
  def main(args: Array[String]) {
    println("greet.")
  }
}

>scalac Test.scala

编译后生成了2个class文件:Test.class,Test$.class,对应2个class:Test,Test$

 

>javap -c Test

Compiled from "Test.scala"

public final class Test {

  public static void main(java.lang.String[]);

    Code:

       0: getstatic     #16                 // Field Test$.MODULE$:LTest$;

       3: aload_0

       4: invokevirtual #18                 // Method Test$.main:([Ljava/lang/String;)V

       7: return

}

 

>javap -c Test$

Compiled from "Test.scala"

public final class Test$ {

  public static Test$ MODULE$;

 

  public static {};

    Code:

       0: new           #2                  // class Test$

       3: invokespecial #12                 // Method "<init>":()V

       6: return

 

  public void main(java.lang.String[]);

    Code:

       0: getstatic     #20                 // Field scala/Predef$.MODULE$:Lscala/Predef$;

       3: ldc           #22                 // String greet.

       5: invokevirtual #26                 // Method scala/Predef$.println:(Ljava/lang/Object;)V

       8: return

}

 

class TestClass(var arg1: Int, var arg2: Int) {
  def this() = {
    this(0, 2);
  }

  def add() : Int = {
    arg1 + arg2
  }
}

object TestClassTest {
  def main(args: Array[String]) = {
    val testClass = new TestClass();

    println("arg1: " + testClass.arg1 + ", arg2: " + testClass.arg2 + ", result: " + testClass.add());

    testClass.arg1 = 100;
    testClass.arg2 = 200;

    println("arg1: " + testClass.arg1 + ", arg2: " + testClass.arg2 + ", result: " + testClass.add());
  }
}

成员变量的隐式get&set方法。如上面的arg1,arg2,在类外部通过testClass.arg1 = 100;testClass.arg2 = 200;进行set,通过testClass.arg1;testClass.arg2进行get。

 

 

Java执行Scala脚本

public class Test {

    private static Logger log = Logger.getLogger(Test.class);

    private static ScriptEngine engine;

    @BeforeClass
    public static void init() {
        engine = ScalaEngine.get();
    }

    public void test(String input) {
        engine.put("input", input);

        URL url = getClass().getResource("test.scala");
        InputStream is = null;
        try {
            is = url.openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Reader reader = new InputStreamReader(is);
        try {
            Object result = engine.eval(reader);
            System.out.println(result);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    @org.junit.Test
    public void test() {
        test("test");
        test("not test");
    }
}











test.scala
var _input = "test"
_input == input










public class ScalaEngine {

    private static Logger log = Logger.getLogger(ScalaEngine.class);

    private static ScriptEngine engine = init();

    private static ScriptEngine init() {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("scala");

        if (engine instanceof IMain) {
            IMain entry = (IMain) engine;
            ISettings isettings = entry.isettings();
            Settings settings = entry.settings();

            MutableSettings.BooleanSetting setting = null;
            try {
                setting = (MutableSettings.BooleanSetting) field(settings, "usejavacp");
                log.info("usejavacp: " + setting.v());
                if (! setting.v()) {
                    field(setting, "v", true, MutableSettings.BooleanSetting.class);
                }
                setting = (MutableSettings.BooleanSetting) field(settings, "usejavacp");
                log.info("usejavacp: " + setting.v());
            } catch (IllegalAccessException e) {
                log.warn(e.getMessage(), e);
            }
        }
        return engine;
    }

    public static ScriptEngine get() {
        return engine;
    }

    public static Object field(Object o, String fieldName, Class<?> klass) throws IllegalAccessException {
        Field valueOps = null;
        try {
            valueOps = klass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            throw new IllegalAccessException(e.getMessage());
        }
        valueOps.setAccessible(true);
        return valueOps.get(o);
    }

    public static Object field(Object o, String fieldName) throws IllegalAccessException {
        Class<?> klass = o.getClass();
        while (klass != Object.class) {
            Class<?> parent = klass.getSuperclass();
            Object value = null;
            try {
                value = field(o, fieldName, klass);
            } catch(IllegalAccessException e) {
                log.info("field " + fieldName + " of " + klass.getName() + " not found, would trying " + parent.getName());
            }
            if (value != null) {
                return value;
            }
            klass = parent;
        }
        throw new IllegalAccessException("field " + fieldName + " not found");
    }

    public static void field(Object o, String fieldName, Object value, Class<?> klass) throws IllegalAccessException {
        Field valueOps = null;
        try {
            valueOps = klass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            throw new IllegalAccessException(e.getMessage());
        }
        valueOps.setAccessible(true);
        valueOps.set(o, value);
    }
}

scala JUnitSuite for unit test

import org.junit.{Before, BeforeClass, Test}
import org.scalatest.junit.JUnitSuite

import scala.util.control.{Breaks, ControlThrowable}
import scala.util.control.Breaks._

private class BreakControl extends ControlThrowable

object BreaksTest {
  @BeforeClass
  def _init : Unit = {

  }
}

class BreaksTest extends JUnitSuite {

  private val breakException = new BreakControl

  def init : Unit = BreaksTest._init

  @Before
  def inittest() : Unit = {}

  @Test
  def test1() : Unit = {
    var i: Int = 0
    breakable {
      while (i < 100) {
        i = i + 1
        if (i == 5) {
          break // break()
        }
      }
    }
    println(i)
    assert (5 == i, "i must eq 5")
  }

  @Test
  def test2() : Unit = {
    val loop = new Breaks

    var i: Int = 0
    loop.breakable {
      while (i < 100) {
        i = i + 1
        if (i == 5) {
          loop.break
        }
      }
    }
    println(i)
    assert (5 == i, "i must eq 5")
  }

  @Test
  def test3() : Unit = {
    var i: Int = 0
    try {
      while (i < 100) {
        i = i + 1
        if (i == 5) {
          throw breakException
        }
      }
    } catch {
      case ex: BreakControl =>
        if (ex ne breakException) throw ex
    }
    println(i)
    assert (5 == i, "i must eq 5")
  }


}

















import java.util
import java.util.Map

import com.shenma.kafka.MessageListener
import org.junit.{Before, BeforeClass, Test}
import org.scalatest.junit.JUnitSuite

object KafkaConsumerTransportTest {

  private var consumerProperties : Map[String, Object] = null

  @BeforeClass
  def _init : Unit = {
    consumerProperties = new util.HashMap[String, Object]
    consumerProperties.put("bootstrap.servers", "192.16.10.44:9092")
    consumerProperties.put("group.id", "test")
    consumerProperties.put("enable.auto.commit", "false")
    consumerProperties.put("retries", "10")
    consumerProperties.put("auto.commit.interval.ms", "1000")
    consumerProperties.put("session.timeout.ms", "15000")
    consumerProperties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    consumerProperties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
  }
}

class KafkaConsumerTransportTest extends JUnitSuite {

  def init : Unit = KafkaConsumerTransportTest._init

  @Before
  def inittest() : Unit = {}

  @Test
  def test() : Unit = {
    var messageListener : MessageListener[String, String] = new TestMagentCatMessageListener()
    var transport : KafkaConsumerTransport[String, String] =
      new KafkaConsumerTransport[String, String](KafkaConsumerTransportTest.consumerProperties, util.Arrays.asList("topic-2018-0925"), messageListener)
    transport run()

    // for test
    try {
      this.synchronized {
        wait()
      }
    } catch {
      case e: InterruptedException => {
        println(e)
        e.printStackTrace()
      }
    }
  }
}

 

 

 

分享到:
评论

相关推荐

    scala sdk scala-2.12.3

    Scala SDK,全称为Scala Software Development Kit,是用于开发Scala应用程序的核心工具集。Scala是一种多范式的编程语言,融合了面向对象和函数式编程的特点,它运行在Java虚拟机(JVM)上,能够充分利用Java生态...

    Scala-2.11.1.zip

    Scala是一种强大的静态类型编程语言,它融合了面向对象和函数式编程的概念,旨在提供一种可扩展的、高效的编程环境。Scala这个名字是“Scalable Language”的缩写,它旨在克服Java的一些局限性,同时保留其平台兼容...

    scala3 scala3 scala3 scala3 scala3

    Scala3,也被称为Scala 3或Dotty,是Scala编程语言的一个重大更新,旨在提高其简洁性、可读性和类型安全性。Scala3的发布标志着该语言的进一步成熟,它引入了一系列改进,旨在解决早期版本中的一些痛点,同时保持对...

    scala2.12.1Windows镜像包

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的概念。这个"scala2.12.1Windows镜像包"是为Windows操作系统设计的Scala编程环境的安装包,版本号为2.12.1。Scala 2.12.x系列是其重要的一个稳定...

    scala学习源代码

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的特性。这个"scala学习源代码"的压缩包文件很可能包含了用于教学或自我学习Scala编程的基础示例。让我们深入了解一下Scala语言的关键概念和特性。 ...

    Scala考试题1

    Scala 是一种多范式的编程语言,它融合了面向对象和函数式编程的特性。下面将详细解释题目中涉及的Scala知识点: 1. **var、val 和 def 的区别**: - `var` 定义可变变量,可以多次赋值。 - `val` 定义不可变变量...

    scala + mybatis 数据库查询

    Scala是一种强大的多范式编程语言,它结合了面向对象和函数式编程的特性。MyBatis则是一款流行的Java持久层框架,主要用于简化数据库操作。在本项目中,"scala + mybatis 数据库查询",我们将探讨如何将Scala与...

    scala-2.12.10.zip

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的概念。这个"scala-2.12.10.zip"文件是Scala编程语言的特定版本——2.12.10,专为Windows操作系统设计的安装包。Scala 2.12.x系列是该语言的一个...

    scala实战高清讲解

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的特性,使得它在处理并发和大数据分析方面表现出色。"Scala实战高清讲解"这本书是学习Scala的宝贵资源,尤其对于那些希望深入理解并提升Scala技能的...

    scala-2.12.14.zip&scala-2.12.11.tgz Linux版本压缩包.rar

    Scala是一种强大的多范式编程语言,它融合了面向对象编程和函数式编程的概念,被广泛应用于大数据处理和分布式计算领域,特别是在Apache Spark等框架中。标题提到的"scala-2.12.14.zip&scala-2.12.11.tgz"是Scala的...

    scala-2.13.8 解压安装版

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的特性。这个"scala-2.13.8 解压安装版"提供了一个无需安装过程的便捷方式来使用Scala开发环境。以下是关于Scala-2.13.8版本的一些关键知识点: 1. ...

    scala-2.12.6.tgz

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的概念,设计目标是提供一种静态类型系统,能够防止程序在运行时出现错误。Scala-2.12.6.tgz是一个针对该语言的最新版本安装包,用于在各种操作系统...

    Programming.in.Scala.pdf

    从上述内容来看,《Programming in Scala.pdf》不仅是一本介绍Scala编程语言的书籍,更是一本为读者提供深入了解和应用Scala语言的实用工具。书籍中的内容覆盖了从基础知识到高级特性的多个层面,确保读者能够在掌握...

    官网scala-2.11.8版本安装包

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的特点,广泛应用于大数据处理、分布式计算和Web开发等领域。Spark是一个基于Scala构建的大数据处理框架,它以其高效、易用和可扩展性而受到业界的...

    scala-2.11.7 包

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的特性。Scala-2.11.7是该语言的一个特定版本,适用于Java虚拟机(JVM)。这个包是官方发布的,确保了其可靠性和兼容性。 在安装Scala-2.11.7时,...

    学习scala好的项目

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的特性,被广泛应用于大数据处理、分布式计算和Web开发等领域。Spark是基于Scala构建的大数据处理框架,其高性能和易用性使得Scala在大数据领域备受...

    最好的scala学习 课件

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的特性,被广泛应用于大数据处理领域,特别是与Apache Spark相结合时。本课件是针对Scala学习者精心准备的资源,旨在帮助你深入理解和掌握Scala的...

    windows版scala-2.11.12.zip

    在这个"windows版scala-2.11.12.zip"压缩包中,包含的是Scala 2.11.12版本的Windows兼容安装文件,这是Scala的一个稳定版本,适用于开发人员在Windows操作系统上进行Scala编程。 Scala 2.11.x系列是Scala的一个主要...

    scala-2.12.13.tgz

    Scala是一种强大的多范式编程语言,它融合了面向对象和函数式编程的概念,为开发者提供了丰富的工具集。这个"scala-2.12.13.tgz"文件是Scala编程语言的一个版本,针对Linux操作系统提供的安装包。tgz(tar.gz)格式...

    scala API 操作hbase表

    在本文中,我们将深入探讨如何使用Scala API操作HBase数据库。HBase是一个分布式、面向列的NoSQL数据库,它构建于Hadoop之上,提供实时访问大量数据的能力。Scala是一种强大的函数式编程语言,与Java虚拟机(JVM)...

Global site tag (gtag.js) - Google Analytics