热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ScalaForJava的一些参考

变量StringyourPastGoodJavaProgrammer;valyourPast:StringGoodJavaProgrammervalyour
     

变量

String yourPast = "Good Java Programmer";

val yourPast : String = "Good Java Programmer"

val yourPast = "Good Java Programmer"

var yourFuture = "Good Java Programmer"

自动类型推断;可变、不可变变量

class Money(amount:Int) amount不是成员变量

class Money(val amount:Int)

val notMuch = new Money(2)

notMuch.amount

class Money(var amount:Int)

val notMuch = new Money(2)

notMuch.amount=3

case classes

public class Money {

private Integer amount;

private String currency;

public Money(Integer amount, String currency) {

this.amount = amount;

this.currency = currency;

}

public Integer getAmount() {

return amount;

}

public void setAmount(Integer amount) {

this.amount = amount;

}

public String getCurrency() {

return currency;

}

public void setCurrency(String currency) {

this.currency = currency;

}

@Override

public int hashCode() {

int hash = 5;

hash = 29 * hash + (this.amount != null ? this.amount.

hashCode() : 0);

hash = 29 * hash + (this.currency != null ? this.currency.

hashCode() : 0);

return hash;

}

@Override

public boolean equals(Object obj) {

if (obj == null) {

return false;

}

if (getClass() != obj.getClass()) {

return false;

}

final Money other = (Money) obj;

return true;

}

@Override

public String toString() {

return "Money{" + "amount=" + amount + ", currency=" +

currency + '}';

}

public Money add(Money other) {

return new Money(this.amount +

other.amount, this.currency);

}

}

case class Money(amount:Int=1, currency:String="USD")  two immutable fields the fields declared in Scala classes are public

case class Money(private val amount: Int, private val currency: String)

to make them private instead, or used  var instead of  val to make the fields mutable.

val defaultAmount = Money()

val fifteenDollars = Money(15,"USD")

val fifteenDollars = Money(15)

val someEuros = Money(currency="EUR")

case class Money(val amount:Int=1, val currency:String="USD"){

def +(other: Money) : MOney= Money(amount + other.amount)

}

Money(12) + Money(34)

collections

Scala collections are, by default, immutable

val numbers = List(1,2,3,4,5,6)

val reversedList = numbers.reverse

val OnlyAFew= numbers drop 2 take 3

cons operator

val numbers = 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: Nil

val simpleList = Nil.::(6)

val twoElementsList = List(6).::(5)

列表串接

val cOncatenatedList= simpleList ::: twoElementsList

val things = List(0,1,true) AnyVal

val things = List(0,1,true,"false") Any

复杂对象列表

val amounts = List(Money(10,"USD"),Money(2,"EUR"),Money(20,"GBP"),

Money(75,"EUR"),Money(100,"USD"),Money(50,"USD"))

Filter

val euros = amounts.filter(mOney=> money.currency=="EUR")

val euros = amounts.filter(x => x.currency=="EUR")

val euros = amounts.filter(_.currency=="EUR")

partition

val allAmounts = amounts.partition(amt => amt.currency=="EUR")

Tuples

val euros = allAmounts._1

val everythingButEuros= allAmounts._2

val (euros,everythingButEuros) = amounts.partition(amt => amt.currency=="EUR")

Map

Map amounts = new HashMap();

amounts.put("USD", 10);

amounts.put("EUR", 2);

val wallet = Map( "USD" -> 10, "EUR" -> 2 )

val someEuros = wallet("EUR")

Option类型

val mayBeSomePounds = wallet.get("GBP")

val updatedWallet = wallet + ("GBP" -> 20)  新的不可变

val tenDollars = "USD"-> 10 Tuple

   

def increment = (x:Int) => x + 1

List(1,2,3,4).map(increment)

List(1,2,3,4) map increment

String Interpolation

val many = 10000.2345

val amount = s"$many euros"

格式化宽度

val amount = f"$many%12.2f euros"

val amount = s"${many*2} euros"

val printedAmounts = amounts map(m=> s"${m.amount} ${m.currency}")

groupBy

groupBy method that transforms a collection into a  Map collection:

val sortedAmounts = amounts groupBy(_.currency)

Scala UnitTest

POM.xml maven依赖文件

•  Dependency for the core scala-library:

org.scala-lang

scala-library

2.10.0

•  Dependency for scalatest (a framework for testing in Scala that supports

JUnit and other styles; we will cover it in detail in Chapter 4, Testing Tools):

org.scalatest

scalatest_2.10

2.0/version>

test

•  Dependency for JUnit to use Java  Assert statements in our test case:

junit

junit

4.11

test

scala-maven-plugin

net.alchim31.maven

scala-maven-plugin

scala-compile-first

process-resources

add-source

compile

scala-test-compile

process-test-resources

testCompile

单元测试代码

import org.junit._

import Assert._

class CustomerScalaTest {

  @Before

  def setUp: Unit = {

  }

  @After

  def tearDown: Unit = {

  }

  @Test

  def testGetCustomerId = {

    System.out.println("getCustomerId")

    val instance = new Customer()

    val expResult: Integer = null

    val result: Integer = instance.getCustomerId()

    assertEquals(expResult, result)

  }

}

Java/Scala Collection转换

./activator console

import java.util.Arrays

val javaList = Arrays.asList(1,2,3,4)

import scala.collection.JavaConverters._

val scalaList = javaList.asScala

val javaListAgain = scalaList.asJava

assert( javaList eq javaListAgain)

JavaBean-style properties

class Company(var name:String)

val sun = new Company("Sun Microsystems")

sun.name

sun.name_=("Oracle")

import scala.beans.BeanProperty

class Company(@BeanProperty var name:String)

val sun = new Company("Sun Microsystems")

sun.getName()

sun.setName("Oracle")

OO

class Customer ( var customerId: Int, var zip: String) {

def this( zip: String) = this(0,zip)

def getCustomerId() = customerId

def setCustomerId(cust: Int): Unit = {

customerId = cust

}

}

val customer = new Customer("123 45")

traits

interface VIPCustomer {

Integer discounts();

}

class Customer(val name:String, val discountCode:String="N" ){

def discounts() : List[Int] = List(5)

override def toString() = "Applied discounts: " + discounts.mkString(" ","%, ","% ")

}

trait VIPCustomer extends Customer {

  override def discounts = super.discounts ::: List(10)

}

trait GoldCustomer extends Customer {

override def discounts =

  if (discountCode.equals("H"))

     super.discounts ::: List(20)

  else super.discounts ::: List(15)

}

object Main {

def main(args: Array[String]) {

val myDiscounts = new Customer("Thomas","H") with VIPCustomer with GoldCustomer

println(myDiscounts)

}

}

scala> Main.main(Array.empty)

Applied discounts: 5%, 10%, 20%

Note that the order in which traits are stacked is important. They are calling each other from right to left.  GoldCustomer is, therefore, the first one to be called.

Static

companion objects

object Main {

def main(args: Array[String]) {

println("Hello Scala World !")

}

}

object Customer {

def apply()= new Customer("default name")

}

class Customer(name:String) {

}

exceptions

public class ConversionSample {

static Integer parse(String numberAsString) {

Integer number = null;

try {

number = Integer.parseInt(numberAsString);

} catch (NumberFormatExceptionnfe) {

System.err.println("Wrong format for "+numberAsString);

} catch (Exception ex) {

System.err.println("An unknown Error has occurred");

}

System.out.println("Parsed Number: "+number);

return number;

}

def parse(numberAsString: String) =

try {

Integer.parseInt(numberAsString)

} catch {

case nfe: NumberFormatException =>

println("Wrong format for number "+numberAsString)

case e: Exception => println("Error when parsing number"+

numberAsString)

}

返回值

case nfe: NumberFormatException =>

println("Wrong format for number "+numberAsString); -1

case _: Throwable =>

println("Error when parsing number "+numberAsString)

-1

scala.util.Left or  scala.util.Right type

case class Failure(val reason: String)

def parse(numberAsString: String) : Either[Failure,Int] =

try {

val result = Integer.parseInt(numberAsString)

Right(result)

} catch {

case _ : Throwable => Left(Failure("Error when parsing

number"))

}

 

String customerLevel = null;

if(amountBought > 3000) {

customerLevel = "Gold";

} else {

customerLevel = "Silver";

}

val amountBought = 5000

val customerLevel = if (amountBought> 3000) "Gold" else "Silver"

Scala的代码风格

IDE

  http://docs.scala-lang.org/style/

Eclipse-based (including all the different versions of Eclipse, Typesafe's own bundled version known as Scala IDE as well as more commercial IDEs such as SpringSourceSTS), IntelliJ IDEA, and NetBeans.

SBT

Simple Build Tool (SBT) http://www.scala-sbt.org/

http://www.scala-sbt.org/0.13/tutorial/Hello.html 例子

http://www.scala-sbt.org/0.13/tutorial/Directories.html 目录结构,Build.sbt是sbt的定义文件

SBT plugins

https://github.com/typesafehub/sbteclipse 基于sbt生成eclipse使用的工程文件

https://github.com/mpeltonen/sbt-idea 基于sbt生成IntelliJ使用的工程文件

https://github.com/dcaoyuan/nbscala/wiki/SbtIntegrationInNetBeans 基于sbt生成Netbeans使用的工程文件

  plugins.sbt中修改以生成

xsbt-web-plugin (available at  https://github.com/JamesEarlDouglas/xsbt-web-plugin ), a useful plugin to create traditional web apps that runs on a servlet container (such as Jetty).

v Plugins.sbt: addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.4.2")

Build.sbt:

  name := "SampleProject"

organization := "com.samples"

version := "1.0"

scalaVersion := "2.10.3"

seq(webSettings :_*)

libraryDependencies += "org.mortbay.jetty" % "jetty" % "6.1.22" % "container"

libraryDependencies += "javax.servlet" % "servlet-api" % "2.5" % "provided"

v sbt eclipse生成了eclipse工程

v 启动web工程

> sbt

> container:start

v War包生成 > package

sbt-assembly

https://github.com/sbt/sbt-assembly

v Plugins.sbt addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.11.2")

v assembly.sbt

import AssemblyKeys._ // put this at the top of the file

assemblySettings

// your assembly settings here

Scalariform

plugins.sbt

addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.2.0")

SBT中运行compile or  test:compile时,即按照scala风格格式化代码

Scala Worksheets

Eclipse中建立的菜单

wpsA257.tmp

每次保存时,可以看到执行的结果

wpsA258.tmp

Java基础库上scala的封装例子

http://dispatch.databinder.net/Dispatch.html HttpClient上的封装

build.sbt添加libraryDependencies += "net.databinder.dispatch" %% "dispatch-core" % "0.11.0"

import dispatch._, Defaults._

val request = url("http://freegeoip.net/xml/www.google.com")

val result = Http( request OK as.String)

val resultAsString = result()

def printer = new scala.xml.PrettyPrinter(90, 2)

for (xml <- citiesAsXML)

println(printer.format(xml))

for comprehension or  for expression

for (sequence) yield expression In the preceding code,  sequence can contain the following components:

•  Generators: They drive the iteration and are written in the following form:

element <- collection

•  Filters: They control the iteration and are written in the following form:

if expression

•  Definitions: They are local variable definitions and are written in the

following form:

variable = expression

for {

elem <- List(1,2,3,4,5)

} yield "T" + elem

for {

word <- List("Hello","Scala")

char <- word

} yield char.isLower

for {

word <- List("Hello","Scala")

char <- word if char.isUpper

} yield char

or {

word <- List("Hello","Scala")

char <- word

lowerChar = char.toLower

} yield lowerChar

测试

ScalaTest ( www.scalatest.org ) and Specs2 ( etorreborre.github.io/specs2/ ). ScalaCheck framework ( www.scalacheck.org )

Typesafe Activator包含必要的插件,项目根下执行> activator eclipse即生成eclipse工程

import org.scalatest.FunSuite

class Test01 extends FunSuite {

test("Very Basic") {

assert(1 == 1)

}

test("Another Very Basic") {

assert("Hello World" == "Hello World")

}

}

> activator

> test-only scalatest.Test01 (or scalatest.Test01.scala)

>~test-only scalatest.Test02  文件修改后自动运行单元测试【continuous mode】

The continuous mode works for the other SBT commands as well, such as  ~run or  ~test

作为Junit的单元测试方式运行

import org.junit.runner.RunWith

import org.scalatest.junit.JUnitRunner

import org.scalatest.FunSuite

@RunWith(classOf[JUnitRunner])

class MyTestSuite extends FunSuite ...

www.seleniumhq.org 功能测试

package scalatest

import org.scalatest._

import org.scalatest.selenium.WebBrowser

import org.openqa.selenium.htmlunit.HtmlUnitDriver

import org.openqa.selenium.firefox.FirefoxDriver

import org.openqa.selenium.WebDriver

class Test08 extends FlatSpec with Matchers with WebBrowser {

implicit val webDriver: WebDriver = new HtmlUnitDriver

go to "http://www.amazon.com"

click on "twotabsearchtextbox"

textField("twotabsearchtextbox").value = "Scala"

submit()

pageTitle should be ("Amazon.com: Scala")

pageSource should include("Scala Cookbook: Recipes")

}

www.scalamock.org

Web框架

alternatives to create web applications range from lightweight frameworks such as Unfiltered, Spray, or Scalatra to full-featured solutions such as the Lift or the Play Frameworks.

http://www.playframework.com/ http://www.playmodules.net

wpsA269.tmp

Web Service

Plugins.sbt

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" %"2.4.0")

addSbtPlugin("org.scalaxb" % "sbt-scalaxb" % "1.1.2")

resolvers += Resolver.sonatypeRepo("public")

build.sbt

import ScalaxbKeys._

name:="wssample"

scalaVersion:="2.10.2"

scalaxbSettings

ibraryDependencies += "net.databinder.dispatch" %% "dispatch-core" %"0.11.0"

libraryDependencies += "org.scalatest" %% "scalatest" % "2.0.M7" %"test"

sourceGenerators in Compile <+= scalaxb in Compile

packageName in scalaxb in Compile := "se.wssample"

XML/JSON

val books =

/>

price="25.50" />

import scala.xml._

val sameBooks = XML.loadString("""

price="30.00"/>

price="25.50"/>

""")

val total = (for {

book <- books \ "book"

price = ( book \ "@price").text.toDouble

quantity = ( book \ "@quantity").text.toInt

} yield price * quantity).sum

val books =

{ List("Programming in Scala,15,30.00","Scala for Java

Developers,10,25.50") map { row => row split "," } map { b =>

title={b(0)} quantity={b(1)} price={b(2)} /> }}

import scala.util.parsing.json._

val result = JSON.parseFull("""

{

"Library": {

"book": [

{

"title": "Scala for Java Developers",

"quantity": 10

},

{

"title": "Programming Scala",

"quantity": 20

}

]}

}

""")

Futures and Promises

Scala Improvement Process (SIP)SIP-14-Futures and Promises

http://en.wikipedia.org/wiki/Futures_and_promises

•  async { } : In this construct,  is the code to

be executed asynchronously.

•  await { } : This construct is included

in an  async block. It suspends the execution of the enclosing  async block

until the argument  Future is completed.

async future

Actor

Reactive Systems

http://www.reactivemanifesto.org/

反应式编程

Misc

MongoDB database, we are going to discover how the Casbah Scala toolkit https://github.com/mongodb/casbah

 

RPEL模式下拷贝部分代码运行

scala> :paste

// Entering paste mode (ctrl-D to finish)

     

推荐阅读
  • Java中包装类的设计原因以及操作方法
    本文主要介绍了Java中设计包装类的原因以及操作方法。在Java中,除了对象类型,还有八大基本类型,为了将基本类型转换成对象,Java引入了包装类。文章通过介绍包装类的定义和实现,解答了为什么需要包装类的问题,并提供了简单易用的操作方法。通过本文的学习,读者可以更好地理解和应用Java中的包装类。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
  • Week04面向对象设计与继承学习总结及作业要求
    本文总结了Week04面向对象设计与继承的重要知识点,包括对象、类、封装性、静态属性、静态方法、重载、继承和多态等。同时,还介绍了私有构造函数在类外部无法被调用、static不能访问非静态属性以及该类实例可以共享类里的static属性等内容。此外,还提到了作业要求,包括讲述一个在网上商城购物或在班级博客进行学习的故事,并使用Markdown的加粗标记和语句块标记标注关键名词和动词。最后,还提到了参考资料中关于UML类图如何绘制的范例。 ... [详细]
  • SpringBoot uri统一权限管理的实现方法及步骤详解
    本文详细介绍了SpringBoot中实现uri统一权限管理的方法,包括表结构定义、自动统计URI并自动删除脏数据、程序启动加载等步骤。通过该方法可以提高系统的安全性,实现对系统任意接口的权限拦截验证。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • JVM 学习总结(三)——对象存活判定算法的两种实现
    本文介绍了垃圾收集器在回收堆内存前确定对象存活的两种算法:引用计数算法和可达性分析算法。引用计数算法通过计数器判定对象是否存活,虽然简单高效,但无法解决循环引用的问题;可达性分析算法通过判断对象是否可达来确定存活对象,是主流的Java虚拟机内存管理算法。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
author-avatar
兔帽儿
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有