SlideShare a Scribd company logo
Java
         Scala

          2009.10 SD2China

Caoyuan (NetBeans Dream Team Memeber)


     http://blogtrader.net/dcaoyuan/
•   JVM
    123.toByte
    "1".toInt
    true.toString


•   val compare = (x: Int, y: Int) => x > y
    compare(1, 2) // result: Boolean = false


•   Java sta&c
                                (   )                Scala   object
    object Dog {
      val whatever = "dog" // static field in Java
    }
    class Dog {
      def callWhatever = Dog.whatever
    }
•   val compare = (x: Int, y: Int) => x > y
    list sortWith compare


•   class AComparator {
      def compare(x: Int, y: Int) = x > y
    }
    list sortWith (new AComparator).compare


•   object annonymous extends scala.Function2[Int, Int, Boolean] {
      override def apply(x: Int, y: Int) = x > y
    }
    list sortWith annonymous


•           sta&c                             object
          (     )
(1)
•   1.+(1)
                                                              ”.” ”()”
    1 + 1
    1.>(0)
    1 > 0
    (1 > 0).&(2 > 1)
    (1 > 0) & 2 > 1
    stack.push(10)
    stack push 10
    stack.pop
    stack pop

•   stack   push {
                                      {...}
      val   a = 1
      val   b = 2
      a +   b
    }

•   def !@#%^&*-<=>?|~:/ = println("noop")
    def √(x: Double) = Math.sqrt(x)
    val Π = Math.Pi
    val r = √(9*Π)

•   ‘<’, ‘>’                                  ’[’ ‘]’
(2)
•   for
    for (i <- List(1, 2)) {
      println(i)
    }
    List(1, 2) foreach {i => println(i)}

    for (i <- List(1, 2)) yield {
      i + 10
    }
    List(1, 2) map {i => i + 10}


•   // synchronized is function call instead of keyword
    def check = synchronized {
      // isInstanceOf is function call instead of keyword
      100.isInstanceOf[String]
    }


•   stack.pop.asInstanceOf[Int] // (Integer) stack.pop() in Java
•                                      return
    val r1 = { // return 3
      val a = 1
      val b = 2
      a + b
    }

    val r2 = if (true) 1 else 2

    val r3 = // return (): Unit
      for (i <- List(1, 2)) {
        println(i)
      }

    val r4 = // return List(11, 12)
      for (i <- List(1, 2)) yield {
        i + 10
      }

    val r5 = // return java.io.File
      try {
        val f = new File("afile")
        f
      } catch {
        case ex: IOException => null
      }
Scala




           (   )


           =
        OO + FP
(1)
•   Scala                              Any Any                JVM

    •   JVM             (byte, short, char, int, long, float, double, boolean) void
    •     Scala     (Byte, Short, Char, Int, Long, Float, Double, Boolean) Unit
           AnyVal
    •   JVM               AnyRef (java.lang.Object)

    // Scala, Array     8
    val arrayOfListOfString = new Array[List[String]](10)
    val arrayOfAny: Array[_] = Array(1, 2)
    // Java
    List<String>[] arrayOfListOfString = new ArrayList<String>[10]



•   Scala                                 Null     Nothing
    •   JVM    null      Null              AnyRef
    •   Nothing Scala              (     AnyVal AnyRef)
(1)
(2)
              -
•      (Invariant): C[T], C is invariant on T
       Tsub Tsup T                         C[Tsub] C[Tsup]    C[T]

•      (Covariant): C[+T], C is covariant on T
       Tsub T                C[Tsub]      C[T]

•      (Contrava&ant): C[‐T], C is contravariant on T
       Tsup T              C[Tsup]       C[T]



    Java                                                ?
    Scala                                        +/-
(2)
class Animal {}
class Dog extends Animal {}
class Fox extends Animal {}


•          Animal                      Animal
class Xian<T> {} // Java                        class Xian[+T]   //

void isAnimalXian(Xian<? extends Animal> in)    def isAnimalXian(in: Xian[Animal])

isAnimalXian(new Xian<Dog>())                   isAnimalXian(new Xian[Dog])
isAnimalXian(new Xian<Fox>())                   isAnimalXian(new Xian[Fox])




•          Dog                  Dog
class Xian<T> {} // Java                        class Xian[-T]   //

void isDogXian(Xian<? super Dog> in)            def isDogXian(in: Xian[Dog])

isDogXian(new Xian[Animal])                     isDogXian(new Xian[Animal])
vs
•
trait Pair[K, V] {                      class PairImpl extends Pair[Dog, Fox] {
  def get(key: K): V                      def get(key: Dog): Fox
  def set(key: K, value: V)               def put(key: Dog, value: Fox)
}                                       }

                                                 =>


•                                                 +                    +
trait Pair {                            class PairImpl extends Pair {
  type K // deferred type                 type K = Dog
  type V // deferred type                 type V = Fox

    def get(key: K): V                      def get(key: K): V
    def set(key: K, value: V)               def set(key: K, value: V)
}                                       }

                                            =>
•          =>     /
•          =>                 type StrToList = HashMap[String, List[String]]
Trait Structural Type
• Trait:     +              =>
• Structural Type:
                                            Type
trait Subject {
  type Observer = {def update(subject: Subject)} // type member

    private var observers = List[Observer]()   // field
    def addObserver(observer: Observer) = observers ::= observer
    def notifyObservers = observers foreach (_.update(this))
}

class Price(var value: Double) {def setValue(v: Double) = value = v}


                                                                  Java Interface
                                                                 Trait
val observablePrice = new Price(10) with Subject {
  override def setValue(v: Double) = {
    super.setValue(v); notifyObservers
  }
}

observablePrice.addObserver(new AnyRef {              update(Subject)      Observer
     def update(subject: Subject) {
       println("price changed")
    }
  })
Trait Self Type
•
    •                    Class                 Trait: OilPrice extends Price with Subject with Market with ....
    •
    •               (Self Type)


trait Subject {self: Price =>
  type Observer = {def update(subject: Price)} // type member

    private var observers = List[Observer]()   // field
                                                                                                                  this   Subject
    def addObserver(observer: Observer) = observers ::= observer
    def notifyObservers = observers foreach (_.update(this))
}

observablePrice.addObserver(new AnyRef { // only need a update(Any) method
     def update(subject: Price) {
       println("price changed to " + subject.value)
     }
  })

• Self Type:
    •       Trait
    •                                        class trait
    •       self       Trait super                   this      self                  self
    •                                Trait
        •
        •                                          class              trait (                   Class      )
apply
•           apply                   <instance>(args)   <instance>.apply(args)
•   apply                     Class
    class Price(var value: Int) {
      def apply() = value // ‘def apply = value’, without ’()’ is bad idea
    }

    object Price {
      def apply(v: Int) = new Price(v)
    }

    val p = Price(10)
    p           // Price@565f0e7d
    p()         // 10
    Price(10)() // 10

•   apply       Scala
    val list = List(1, 2, 3)         // List.apply[A](xs: A*)
    val array = Array("a", "b", "c") // Array.apply[T](xs: T*)
    val map = Map("a" -> 1,
                  "b" -> 2,
                  "c" -> 3) // MapFactory.apply[A, B](elems: (A, B)*)

    array(0) // array.apply(index): "a"
    map("a") // map.apply(key): 1
•   Java Switch                  (          Java7) Scala
    val str = "abcdef"
    str.toSeq match {
      case Seq('a', 'b', rest@_*) => println(rest) // cdef
      case _ => println("no match")
    }

    var any: Any = _
    any match {
      case "scala" | "java" => "string"
      case i: Int if i > 10 => "int > 10"
      case `str` => "abcdef"
      case _: String => "string type"
      case hd :: tail => "List"
      case _ => "other"
    }

    case class Address(coutry: String, city: String, street: String, no: Int)
    case class Person(name: String, age: Int, address: Address)

    val p = Person("Wang wu", 12, Address("China", "Beijing", "Chang'an", 10))

    p match {
      case Person(name, age, Address(coutry, city, street, no)) =>
        println(name + "|" + coutry + "|" + city + "|" + street + "|" + no)
    }
Scala
• Existential type (    Java   )
• Implicit type * (                              )
• val, var, lazy val (                       )
• Partial function * (                               )
• Primary constructor (                          apply)
• Accessor properties (Why getter, setter?        )
• XML Process (          )



*      DSL
(DSL     )
•   Actors
    class Ping(count: Int, pong: Actor) extends Actor {
      def act() {
        var pingsLeft = count - 1
        pong ! Ping
        while (true) {
          receive {                                                {...}
            case Pong =>
              if (pingsLeft % 1000 == 0)
                println("Pong”)
              if (pingsLeft > 0) {
                pong ! Ping
                pingsLeft -= 1
              } else {
                pong ! Stop
                exit()
              }}}}}
•   Bill Venners scalatest
    class StackSpec extends FlatSpec with ShouldMatchers {

        "A Stack" should "pop values in last-in-first-out order" in {
          val stack = new Stack[Int]
          stack.push(1)
          stack.push(2)
          stack.pop() should equal (2)                          should
          stack.pop() should equal (1)
        }

        it should "throw NoSuchElementException if an empty stack is popped" in {
          val emptyStack = new Stack[String]
          evaluating { emptyStack.pop() } should produce [NoSuchElementException]
        }
    }
Scala                   Java

Scala Java
• Scala            Java
   • Array
• Scala                Java       Java
   •          object
• Scala
   • Actors   Packrat Parser




                          Scala
Scala        Java


• Scala
•       Java         Scala(    nio )
•       Scala   (   liftweb)
• IDE
IDE

• IntelliJ Idea
  •5
  •

• Eclipse
  •       Sean McDirmid
  •       1              (Miles Sabin)
  • Scala             Martin IDE


• NetBeans
  •                (dcaoyuan)
  • 2007   LL(K)
  • 2008         PEGs
  • 2008         Scala              Hacking NetBeans Innovation Grant
  • 2009 8           Scala    Scala             Martin IDE
IDE               -NetBeans
•
    •
    •
    •
    •
    •
    •
    •
    •
    •
    •         HTML
    •
    •
    • Java/Scala
    •
    •            import
    •
    •
    • Maven
•
    • NetBeans 6.7.x                     7000
    • NetBeans 6.8m2            Scala-2.8.0     beta
       http://wiki.netbeans.org/Scala68v1
Scala for NetBeans
Q&A

More Related Content

What's hot

Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
futurespective
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Sanjeev_Knoldus
 
Scalaz
ScalazScalaz
Scalaz
mpilquist
 
Scala Intro
Scala IntroScala Intro
Scala Intro
Paolo Platter
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
oxbow_lakes
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kirill Rozov
 
All about scala
All about scalaAll about scala
All about scala
Yardena Meymann
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
Bert Van Vreckem
 
Scala
ScalaScala
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - Intro
David Copeland
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
Razvan Cojocaru
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
Maxim Novak
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
Michael Galpin
 
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
Derek Chen-Becker
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
Ruslan Shevchenko
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 

What's hot (20)

Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
 
Scalaz
ScalazScalaz
Scalaz
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Practical scalaz
Practical scalazPractical scalaz
Practical scalaz
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
All about scala
All about scalaAll about scala
All about scala
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Scala
ScalaScala
Scala
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - Intro
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
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 jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 

Similar to Scala-对Java的修正和超越

(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
 
Scala
ScalaScala
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
Mohsen Zainalpour
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
bpstudy
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
Xing
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
Werner Hofstra
 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritance
Alexey Raga
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
intelliyole
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
gabalese
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
futurespective
 
Meet scala
Meet scalaMeet scala
Meet scala
Wojciech Pituła
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
jeffz
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Debasish Ghosh
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々Scalaプログラミング
Tomoharu ASAMI
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
wpgreenway
 
Scala introduction
Scala introductionScala introduction
Scala introduction
vito jeng
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
Jorge Vásquez
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
Vasil Remeniuk
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 

Similar to Scala-对Java的修正和超越 (20)

(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?
 
Scala
ScalaScala
Scala
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
Type classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritanceType classes 101 - classification beyond inheritance
Type classes 101 - classification beyond inheritance
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
楽々Scalaプログラミング
楽々Scalaプログラミング楽々Scalaプログラミング
楽々Scalaプログラミング
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
A Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIOA Prelude of Purity: Scaling Back ZIO
A Prelude of Purity: Scaling Back ZIO
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 

Recently uploaded

GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 

Recently uploaded (20)

GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 

Scala-对Java的修正和超越

  • 1. Java Scala 2009.10 SD2China Caoyuan (NetBeans Dream Team Memeber) http://blogtrader.net/dcaoyuan/
  • 2. JVM 123.toByte "1".toInt true.toString • val compare = (x: Int, y: Int) => x > y compare(1, 2) // result: Boolean = false • Java sta&c ( ) Scala object object Dog { val whatever = "dog" // static field in Java } class Dog { def callWhatever = Dog.whatever }
  • 3. val compare = (x: Int, y: Int) => x > y list sortWith compare • class AComparator { def compare(x: Int, y: Int) = x > y } list sortWith (new AComparator).compare • object annonymous extends scala.Function2[Int, Int, Boolean] { override def apply(x: Int, y: Int) = x > y } list sortWith annonymous • sta&c object ( )
  • 4. (1) • 1.+(1) ”.” ”()” 1 + 1 1.>(0) 1 > 0 (1 > 0).&(2 > 1) (1 > 0) & 2 > 1 stack.push(10) stack push 10 stack.pop stack pop • stack push { {...} val a = 1 val b = 2 a + b } • def !@#%^&*-<=>?|~:/ = println("noop") def √(x: Double) = Math.sqrt(x) val Π = Math.Pi val r = √(9*Π) • ‘<’, ‘>’ ’[’ ‘]’
  • 5. (2) • for for (i <- List(1, 2)) { println(i) } List(1, 2) foreach {i => println(i)} for (i <- List(1, 2)) yield { i + 10 } List(1, 2) map {i => i + 10} • // synchronized is function call instead of keyword def check = synchronized { // isInstanceOf is function call instead of keyword 100.isInstanceOf[String] } • stack.pop.asInstanceOf[Int] // (Integer) stack.pop() in Java
  • 6. return val r1 = { // return 3 val a = 1 val b = 2 a + b } val r2 = if (true) 1 else 2 val r3 = // return (): Unit for (i <- List(1, 2)) { println(i) } val r4 = // return List(11, 12) for (i <- List(1, 2)) yield { i + 10 } val r5 = // return java.io.File try { val f = new File("afile") f } catch { case ex: IOException => null }
  • 7. Scala ( ) = OO + FP
  • 8.
  • 9. (1) • Scala Any Any JVM • JVM (byte, short, char, int, long, float, double, boolean) void • Scala (Byte, Short, Char, Int, Long, Float, Double, Boolean) Unit AnyVal • JVM AnyRef (java.lang.Object) // Scala, Array 8 val arrayOfListOfString = new Array[List[String]](10) val arrayOfAny: Array[_] = Array(1, 2) // Java List<String>[] arrayOfListOfString = new ArrayList<String>[10] • Scala Null Nothing • JVM null Null AnyRef • Nothing Scala ( AnyVal AnyRef)
  • 10. (1)
  • 11. (2) - • (Invariant): C[T], C is invariant on T Tsub Tsup T C[Tsub] C[Tsup] C[T] • (Covariant): C[+T], C is covariant on T Tsub T C[Tsub] C[T] • (Contrava&ant): C[‐T], C is contravariant on T Tsup T C[Tsup] C[T] Java ? Scala +/-
  • 12. (2) class Animal {} class Dog extends Animal {} class Fox extends Animal {} • Animal Animal class Xian<T> {} // Java class Xian[+T] // void isAnimalXian(Xian<? extends Animal> in) def isAnimalXian(in: Xian[Animal]) isAnimalXian(new Xian<Dog>()) isAnimalXian(new Xian[Dog]) isAnimalXian(new Xian<Fox>()) isAnimalXian(new Xian[Fox]) • Dog Dog class Xian<T> {} // Java class Xian[-T] // void isDogXian(Xian<? super Dog> in) def isDogXian(in: Xian[Dog]) isDogXian(new Xian[Animal]) isDogXian(new Xian[Animal])
  • 13. vs • trait Pair[K, V] { class PairImpl extends Pair[Dog, Fox] { def get(key: K): V def get(key: Dog): Fox def set(key: K, value: V) def put(key: Dog, value: Fox) } } => • + + trait Pair { class PairImpl extends Pair { type K // deferred type type K = Dog type V // deferred type type V = Fox def get(key: K): V def get(key: K): V def set(key: K, value: V) def set(key: K, value: V) } } => • => / • => type StrToList = HashMap[String, List[String]]
  • 14. Trait Structural Type • Trait: + => • Structural Type: Type trait Subject { type Observer = {def update(subject: Subject)} // type member private var observers = List[Observer]() // field def addObserver(observer: Observer) = observers ::= observer def notifyObservers = observers foreach (_.update(this)) } class Price(var value: Double) {def setValue(v: Double) = value = v} Java Interface Trait val observablePrice = new Price(10) with Subject { override def setValue(v: Double) = { super.setValue(v); notifyObservers } } observablePrice.addObserver(new AnyRef { update(Subject) Observer def update(subject: Subject) { println("price changed") } })
  • 15. Trait Self Type • • Class Trait: OilPrice extends Price with Subject with Market with .... • • (Self Type) trait Subject {self: Price => type Observer = {def update(subject: Price)} // type member private var observers = List[Observer]() // field this Subject def addObserver(observer: Observer) = observers ::= observer def notifyObservers = observers foreach (_.update(this)) } observablePrice.addObserver(new AnyRef { // only need a update(Any) method def update(subject: Price) { println("price changed to " + subject.value) } }) • Self Type: • Trait • class trait • self Trait super this self self • Trait • • class trait ( Class )
  • 16. apply • apply <instance>(args) <instance>.apply(args) • apply Class class Price(var value: Int) { def apply() = value // ‘def apply = value’, without ’()’ is bad idea } object Price { def apply(v: Int) = new Price(v) } val p = Price(10) p // Price@565f0e7d p() // 10 Price(10)() // 10 • apply Scala val list = List(1, 2, 3) // List.apply[A](xs: A*) val array = Array("a", "b", "c") // Array.apply[T](xs: T*) val map = Map("a" -> 1, "b" -> 2, "c" -> 3) // MapFactory.apply[A, B](elems: (A, B)*) array(0) // array.apply(index): "a" map("a") // map.apply(key): 1
  • 17. Java Switch ( Java7) Scala val str = "abcdef" str.toSeq match { case Seq('a', 'b', rest@_*) => println(rest) // cdef case _ => println("no match") } var any: Any = _ any match { case "scala" | "java" => "string" case i: Int if i > 10 => "int > 10" case `str` => "abcdef" case _: String => "string type" case hd :: tail => "List" case _ => "other" } case class Address(coutry: String, city: String, street: String, no: Int) case class Person(name: String, age: Int, address: Address) val p = Person("Wang wu", 12, Address("China", "Beijing", "Chang'an", 10)) p match { case Person(name, age, Address(coutry, city, street, no)) => println(name + "|" + coutry + "|" + city + "|" + street + "|" + no) }
  • 18. Scala • Existential type ( Java ) • Implicit type * ( ) • val, var, lazy val ( ) • Partial function * ( ) • Primary constructor ( apply) • Accessor properties (Why getter, setter? ) • XML Process ( ) * DSL
  • 19. (DSL ) • Actors class Ping(count: Int, pong: Actor) extends Actor { def act() { var pingsLeft = count - 1 pong ! Ping while (true) { receive { {...} case Pong => if (pingsLeft % 1000 == 0) println("Pong”) if (pingsLeft > 0) { pong ! Ping pingsLeft -= 1 } else { pong ! Stop exit() }}}}} • Bill Venners scalatest class StackSpec extends FlatSpec with ShouldMatchers { "A Stack" should "pop values in last-in-first-out order" in { val stack = new Stack[Int] stack.push(1) stack.push(2) stack.pop() should equal (2) should stack.pop() should equal (1) } it should "throw NoSuchElementException if an empty stack is popped" in { val emptyStack = new Stack[String] evaluating { emptyStack.pop() } should produce [NoSuchElementException] } }
  • 20. Scala Java Scala Java • Scala Java • Array • Scala Java Java • object • Scala • Actors Packrat Parser Scala
  • 21. Scala Java • Scala • Java Scala( nio ) • Scala ( liftweb) • IDE
  • 22. IDE • IntelliJ Idea •5 • • Eclipse • Sean McDirmid • 1 (Miles Sabin) • Scala Martin IDE • NetBeans • (dcaoyuan) • 2007 LL(K) • 2008 PEGs • 2008 Scala Hacking NetBeans Innovation Grant • 2009 8 Scala Scala Martin IDE
  • 23. IDE -NetBeans • • • • • • • • • • • HTML • • • Java/Scala • • import • • • Maven • • NetBeans 6.7.x 7000 • NetBeans 6.8m2 Scala-2.8.0 beta http://wiki.netbeans.org/Scala68v1
  • 25. Q&A