SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
Hello Scala
JINLIANG OU
2014 04
The First Example
http://git.n.xiaomi.com/oujinliang/scala-intro
假设我们要解析这个文件,对符合条件的每一行构造一个对象(Xmq), 构造一个列表,对某两列排序,然后对这
个列表的每一个对象进行操作(print):
http://git.n.xiaomi.com/oujinliang/scala-intro/blob/master/xmq.txt
Java Solution:
http://git.n.xiaomi.com/oujinliang/scala-intro/blob/master/src/main/java/org/jinou/javasample/ParseXmqNodes.java
Scala Solution:
http://git.n.xiaomi.com/oujinliang/scala-intro/blob/master/src/main/scala/org/jinou/scalasample/ParseXmqNodes.scala
About Scala
Scalable Language 的缩写
By Martin Ordersky (Generic Java 作者,最初 javac 的参考实现的作者)
James Gosling (Creator of Java):
◦ "Which Programming Language would you use *now* on top of JVM, except Java?".
◦ The answer was surprisingly fast and very clear: - Scala.
James Strachan (Created Groovy in 2003):
◦ I can honestly say if someone had shown me the Programming in Scala book by by Martin Odersky, Lex
Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.
◦ http://macstrac.blogspot.com/2009/04/scala-as-long-term-replacement-for.html
About Scala (features)
oGeneral purpose Language
oJVM based (full inter-op with Java, community, libraries)
oFast
oStatically Typed (Type safe)
oObject Oriented
oFunctional
oConcurrency
oConcise and Expressive
oPowerful, highly Scalable,
oProductivity
Scala Is Used By
Companies:
◦ Twitter, LinkedIn, Siemens, Amazon, SONY, Foursquare, …
Libraries and Frameworks
◦ Akka, Kafka, Finagle, Spark, Play! Lift, …
Scala 是简洁的 Java
Type less, do more.
Less code, fewer bugs.
一些东西是可以省略的
表达式后的分号
◦ 基本都是不需要的(除非你想一行写多条,不建议)
return 关键字
◦ 大部分可以省略, 除了少数情况必须从函数中间返回
没有参数的函数调用和声明
◦ a.toString => a.toString()
方法调用中间的 .
◦ 在某些 DSL 的场合
◦ nameList foreach println => nameList.foreach(n => println(n))
类型 (见下页)
Type Inference
类型推导, 静态语言写出动态语言的感觉. 在能推导出类型的时候,可以省略类型
值或变量的类型
◦ val sum = 1 + 2 + 3
◦ 和下面的等价,Compiler 推导出类型为 Int
◦ val sum : Int = 1 + 2 + 3
◦ var names = List(“Steve”, “Mike”, “Bob”)
◦ List[String]
◦ val map = Map(1234 -> Person(“Jim”, 18), 5678 -> Person(“Jack”, 22))
◦ Map[Int, Person]
函数的返回类型 (def 是函数定义的关键字)
◦ def getName = “myName”
◦ 等价于:
◦ def getName() : String = “myName”
简洁的表达
简化的类定义:
class Xmq(chid:Int, start:Long, end:Long, host:String, port:Int, site:String) {
override def toString = “xxxx”
}
val xmq = new Xmq(1, 1, 10000, “localhost”, 7915, “site0”)
利用高价函数进行简化
val list = List(1, 2, 3, 4, 5, 6)
val hasTwo = list.exists(_ == 2) // true
val even = list.filter(_ % 2 ==0) // List(2, 4, 6)
转换
val id = “12345”.toInt
val list = Array(“a”, “b”, “c”).toList
val set = list.toSet
其它有用的特性
Tuple:
◦ 有的时候你需要组合两个或三个对象,但创建一个类又太 heavy.
◦ val (host, port) = getHostAndPort(xxxx)
Default Parameter value, Named Parameter
Raw String:
◦ Java 中字符串转义,拼接太麻烦了,
◦ 可读性很重要
"""[(d+),s*(d+),s*(d+),s*"(.+)",s*(d+),s*"(.+)".*]""? (Scala)
Or
"[(d+),s*(d+),s*(d+),s*"(.+)",s*(d+),s*"(.+)".*]" (Java)
val usage = """Usage:
1. xxxx
2. yyyy
3. xxxx
"""
XML
case class Book(val name: String, val price: Int)
object XmlSample {
def main(args: Array[String]) {
val xml = getBooksXml("computer", 2, List(Book("C Language", 10), Book("Java Memory Model", 40)))
println(xml)
println(xml  "@category") // get the attribute
}
def getBooksXml(category: String, version: Int, books: List[Book]): Node =
<books category={category} version={version.toString}> { books.map(getBookXml) } </books>
def getBookXml(book: Book) = <book name={book.name} price={book.price.toString} />
}
<books version="2" category="computer"> <book name="C Language" price="10"></book><book name="Java Memory Model" price="40"></book> </books>
computer
Scala is Object Oriented
It’s PURE OO
一切都是对象, Scala 是面向对象的,没有Java 中的所谓静态等非对象的东西
(想想 Java 有哪些不是 pure OO 的?基本类型,静态类?)
◦ 1 + 2
◦ 1.+(2)
OO 有哪些特性?哪些原则?
Class/Object/Trait
object vs. class
◦ class 和 Java 中的概念一样,用来创建对象的
◦ object is singleton !
◦ 忘记各种复杂的 singleton 的构造方式吧,忘记 double-checked locking
Trait
◦ Interface in Java, 可以有预定义的方法 (Java 8 ?)
◦ Mixin (解决Java 中无法多继承的问题)
object IdGenerator {
private val acc = new AtomicInteger(0)
def nextId() = acc.incrementAndGet
}
val newId = IdGenerator.nextId()
Scala is Functional
Function is first-class citizen
◦ 单独声明一个函数:
def foo(a: Int) = {
a * 2
}
foo(3)
◦ 函数作为变量
val plus2 = (x: Int) => x + 2
plus2(3) // 5
◦ 函数作为参数,返回值都可以
Higher Order Function
a higher-order function is a function that does at least one of the following:
◦ takes one or more functions as an input
◦ outputs a function
val plus2 = (x: Int) => x + 2
val nums = List(1,2,3,4)
// higher order functions
val double = nums.map(_*2) //
◦ or nums.map(n => n * 2) // List(2,4,6,8)
val allPlus2 = nums.map(plus2) // List(3,4,5,6)
val reduce = nums.reduce(_ + _) // 10
val result = nums.filter(_ > 2) // List(3,4)
Higher-order function example
def withClient[T](f: Client => T) = {
val client = getClient
try {
f(client)
} finally {
client.close
}
}
val i: Int = withClient( _.getIntValue() )
val s: String = withClient( _.getStringValue() )
Pattern Match
Java 的 switch/case 太弱了。
Scala 可以匹配 (基本类型,String, 正则表达式,List, case 对象… )
def what(any: Any) = any match {
case i: Int => "I'm int"
case s: String if s.startsWith("s") => "Starts with s "
case "hello" => "This is a hello"
case _ => "what ever "
}
what(123)
what(“hello”)
what(“scala”)
其他高级货
o 并发, actor, Akka, 并发collections
o Generic, variance, co-variance
o Implicit conversions
o Partially applied functions
o Currying
o For comprehensions
o Macro
o…
使用 Scala
IDE:
◦ Eclipse (http://scala-ide.org, 官方支持, 很好用)
◦ IntelliJ IDEA (with the Scala plugin, JetBrains官方插件, 很好用)
◦ NetBeans (with the Scala plugin, 没用过 )
Build Tool:
◦ Sbt (simple build tool, Scala项目默认都使用的)
◦ Maven (with plugin) 我在一些项目里使用这个,混合 Java + Scala
◦ Ant..
Test
◦ 可以使用 Junit
◦ 也可以使用专门给Scala 设计的: specs, scala test …
Libraries and Frameworks
◦ 找得到Scala 的用Scala 的,找不到就用 Java 的!
◦ https://wiki.scala-lang.org/display/SW/Tools+and+Libraries
缺点
编译速度
◦ 使用 IDE 的增量编译
二进制不兼容
◦ 使用版本化
语法越来越复杂
◦ 易上手,难精通
◦ 开始不要使用高级功能
◦ 应用开发和库开发需要使用的技能是不同的
◦ 不要炫技
用的人少, 招聘难
◦ 学吧, 用 Scala 的人越来越多了。
学习Scala
开始:
◦ http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html
◦ http://twitter.github.io/scala_school/ (http://twitter.github.io/scala_school/zh_cn/index.html )
全面学习
◦ Programming in Scala
Effective Scala
◦ http://twitter.github.io/effectivescala/index.html

Más contenido relacionado

La actualidad más candente

Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSOswald Campesato
 
Snmp class
Snmp classSnmp class
Snmp classaduitsis
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Java 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJava 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJason Swartz
 
Text processing
Text processingText processing
Text processingIcancode
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode CompilerDonal Fellows
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
 
Pig Introduction to Pig
Pig Introduction to PigPig Introduction to Pig
Pig Introduction to PigChris Wilkes
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
What is row level isolation on cassandra
What is row level isolation on cassandraWhat is row level isolation on cassandra
What is row level isolation on cassandraKazutaka Tomita
 

La actualidad más candente (20)

Functional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJSFunctional Reactive Programming (FRP): Working with RxJS
Functional Reactive Programming (FRP): Working with RxJS
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Snmp class
Snmp classSnmp class
Snmp class
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Java 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJava 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason Swartz
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Text processing
Text processingText processing
Text processing
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
 
Meetup slides
Meetup slidesMeetup slides
Meetup slides
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Pig Introduction to Pig
Pig Introduction to PigPig Introduction to Pig
Pig Introduction to Pig
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 
Scala
ScalaScala
Scala
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
What is row level isolation on cassandra
What is row level isolation on cassandraWhat is row level isolation on cassandra
What is row level isolation on cassandra
 

Similar a Hello scala

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 
Javascript basics
Javascript basicsJavascript basics
Javascript basicsFin Chen
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingMeir Maor
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVMJarek Ratajski
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108Mathias Herberts
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 

Similar a Hello scala (20)

Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Exception Handling in Scala
Exception Handling in ScalaException Handling in Scala
Exception Handling in Scala
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVM
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108Artimon - Apache Flume (incubating) NYC Meetup 20111108
Artimon - Apache Flume (incubating) NYC Meetup 20111108
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Scala
ScalaScala
Scala
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 

Último

Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 

Último (20)

Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 

Hello scala

  • 2. The First Example http://git.n.xiaomi.com/oujinliang/scala-intro 假设我们要解析这个文件,对符合条件的每一行构造一个对象(Xmq), 构造一个列表,对某两列排序,然后对这 个列表的每一个对象进行操作(print): http://git.n.xiaomi.com/oujinliang/scala-intro/blob/master/xmq.txt Java Solution: http://git.n.xiaomi.com/oujinliang/scala-intro/blob/master/src/main/java/org/jinou/javasample/ParseXmqNodes.java Scala Solution: http://git.n.xiaomi.com/oujinliang/scala-intro/blob/master/src/main/scala/org/jinou/scalasample/ParseXmqNodes.scala
  • 3. About Scala Scalable Language 的缩写 By Martin Ordersky (Generic Java 作者,最初 javac 的参考实现的作者) James Gosling (Creator of Java): ◦ "Which Programming Language would you use *now* on top of JVM, except Java?". ◦ The answer was surprisingly fast and very clear: - Scala. James Strachan (Created Groovy in 2003): ◦ I can honestly say if someone had shown me the Programming in Scala book by by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy. ◦ http://macstrac.blogspot.com/2009/04/scala-as-long-term-replacement-for.html
  • 4. About Scala (features) oGeneral purpose Language oJVM based (full inter-op with Java, community, libraries) oFast oStatically Typed (Type safe) oObject Oriented oFunctional oConcurrency oConcise and Expressive oPowerful, highly Scalable, oProductivity
  • 5. Scala Is Used By Companies: ◦ Twitter, LinkedIn, Siemens, Amazon, SONY, Foursquare, … Libraries and Frameworks ◦ Akka, Kafka, Finagle, Spark, Play! Lift, …
  • 6. Scala 是简洁的 Java Type less, do more. Less code, fewer bugs.
  • 7. 一些东西是可以省略的 表达式后的分号 ◦ 基本都是不需要的(除非你想一行写多条,不建议) return 关键字 ◦ 大部分可以省略, 除了少数情况必须从函数中间返回 没有参数的函数调用和声明 ◦ a.toString => a.toString() 方法调用中间的 . ◦ 在某些 DSL 的场合 ◦ nameList foreach println => nameList.foreach(n => println(n)) 类型 (见下页)
  • 8. Type Inference 类型推导, 静态语言写出动态语言的感觉. 在能推导出类型的时候,可以省略类型 值或变量的类型 ◦ val sum = 1 + 2 + 3 ◦ 和下面的等价,Compiler 推导出类型为 Int ◦ val sum : Int = 1 + 2 + 3 ◦ var names = List(“Steve”, “Mike”, “Bob”) ◦ List[String] ◦ val map = Map(1234 -> Person(“Jim”, 18), 5678 -> Person(“Jack”, 22)) ◦ Map[Int, Person] 函数的返回类型 (def 是函数定义的关键字) ◦ def getName = “myName” ◦ 等价于: ◦ def getName() : String = “myName”
  • 9. 简洁的表达 简化的类定义: class Xmq(chid:Int, start:Long, end:Long, host:String, port:Int, site:String) { override def toString = “xxxx” } val xmq = new Xmq(1, 1, 10000, “localhost”, 7915, “site0”) 利用高价函数进行简化 val list = List(1, 2, 3, 4, 5, 6) val hasTwo = list.exists(_ == 2) // true val even = list.filter(_ % 2 ==0) // List(2, 4, 6) 转换 val id = “12345”.toInt val list = Array(“a”, “b”, “c”).toList val set = list.toSet
  • 10. 其它有用的特性 Tuple: ◦ 有的时候你需要组合两个或三个对象,但创建一个类又太 heavy. ◦ val (host, port) = getHostAndPort(xxxx) Default Parameter value, Named Parameter Raw String: ◦ Java 中字符串转义,拼接太麻烦了, ◦ 可读性很重要 """[(d+),s*(d+),s*(d+),s*"(.+)",s*(d+),s*"(.+)".*]""? (Scala) Or "[(d+),s*(d+),s*(d+),s*"(.+)",s*(d+),s*"(.+)".*]" (Java) val usage = """Usage: 1. xxxx 2. yyyy 3. xxxx """
  • 11. XML case class Book(val name: String, val price: Int) object XmlSample { def main(args: Array[String]) { val xml = getBooksXml("computer", 2, List(Book("C Language", 10), Book("Java Memory Model", 40))) println(xml) println(xml "@category") // get the attribute } def getBooksXml(category: String, version: Int, books: List[Book]): Node = <books category={category} version={version.toString}> { books.map(getBookXml) } </books> def getBookXml(book: Book) = <book name={book.name} price={book.price.toString} /> } <books version="2" category="computer"> <book name="C Language" price="10"></book><book name="Java Memory Model" price="40"></book> </books> computer
  • 12. Scala is Object Oriented It’s PURE OO 一切都是对象, Scala 是面向对象的,没有Java 中的所谓静态等非对象的东西 (想想 Java 有哪些不是 pure OO 的?基本类型,静态类?) ◦ 1 + 2 ◦ 1.+(2) OO 有哪些特性?哪些原则?
  • 13. Class/Object/Trait object vs. class ◦ class 和 Java 中的概念一样,用来创建对象的 ◦ object is singleton ! ◦ 忘记各种复杂的 singleton 的构造方式吧,忘记 double-checked locking Trait ◦ Interface in Java, 可以有预定义的方法 (Java 8 ?) ◦ Mixin (解决Java 中无法多继承的问题) object IdGenerator { private val acc = new AtomicInteger(0) def nextId() = acc.incrementAndGet } val newId = IdGenerator.nextId()
  • 14. Scala is Functional Function is first-class citizen ◦ 单独声明一个函数: def foo(a: Int) = { a * 2 } foo(3) ◦ 函数作为变量 val plus2 = (x: Int) => x + 2 plus2(3) // 5 ◦ 函数作为参数,返回值都可以
  • 15. Higher Order Function a higher-order function is a function that does at least one of the following: ◦ takes one or more functions as an input ◦ outputs a function val plus2 = (x: Int) => x + 2 val nums = List(1,2,3,4) // higher order functions val double = nums.map(_*2) // ◦ or nums.map(n => n * 2) // List(2,4,6,8) val allPlus2 = nums.map(plus2) // List(3,4,5,6) val reduce = nums.reduce(_ + _) // 10 val result = nums.filter(_ > 2) // List(3,4)
  • 16. Higher-order function example def withClient[T](f: Client => T) = { val client = getClient try { f(client) } finally { client.close } } val i: Int = withClient( _.getIntValue() ) val s: String = withClient( _.getStringValue() )
  • 17. Pattern Match Java 的 switch/case 太弱了。 Scala 可以匹配 (基本类型,String, 正则表达式,List, case 对象… ) def what(any: Any) = any match { case i: Int => "I'm int" case s: String if s.startsWith("s") => "Starts with s " case "hello" => "This is a hello" case _ => "what ever " } what(123) what(“hello”) what(“scala”)
  • 18. 其他高级货 o 并发, actor, Akka, 并发collections o Generic, variance, co-variance o Implicit conversions o Partially applied functions o Currying o For comprehensions o Macro o…
  • 19. 使用 Scala IDE: ◦ Eclipse (http://scala-ide.org, 官方支持, 很好用) ◦ IntelliJ IDEA (with the Scala plugin, JetBrains官方插件, 很好用) ◦ NetBeans (with the Scala plugin, 没用过 ) Build Tool: ◦ Sbt (simple build tool, Scala项目默认都使用的) ◦ Maven (with plugin) 我在一些项目里使用这个,混合 Java + Scala ◦ Ant.. Test ◦ 可以使用 Junit ◦ 也可以使用专门给Scala 设计的: specs, scala test … Libraries and Frameworks ◦ 找得到Scala 的用Scala 的,找不到就用 Java 的! ◦ https://wiki.scala-lang.org/display/SW/Tools+and+Libraries
  • 20. 缺点 编译速度 ◦ 使用 IDE 的增量编译 二进制不兼容 ◦ 使用版本化 语法越来越复杂 ◦ 易上手,难精通 ◦ 开始不要使用高级功能 ◦ 应用开发和库开发需要使用的技能是不同的 ◦ 不要炫技 用的人少, 招聘难 ◦ 学吧, 用 Scala 的人越来越多了。
  • 21. 学习Scala 开始: ◦ http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html ◦ http://twitter.github.io/scala_school/ (http://twitter.github.io/scala_school/zh_cn/index.html ) 全面学习 ◦ Programming in Scala Effective Scala ◦ http://twitter.github.io/effectivescala/index.html