SlideShare a Scribd company logo
1 of 53
Download to read offline
<moriyoshi@gmail.com>
Java 1.5
Pizza    GJ
                 Scala
        Funnel
public class Application {
                public static void main(String[] args) {
                  System.out.println(”Hello, World”);
                }
              }


object Application {
  def main(args: Array[String]) {
    println(”Hello, World”)
  }
}
//
val numbers = 1.until(10) // 1, 2, ..., 10
println(numbers(5)) // ”6”




//
println((5).+(3)) // ”8”
println(5 + 3) //    ”()”   ”.”
println(5.+(3)) //            5.0+(3)

    //
    println(1 until 10)
//
//   (?)
//      String        Unit
// println puts
val puts: String => Unit = println
puts(”hey!”)




def fun1(x: Int): Int = {
  def fun2(y: Int): Int = x * y
  fun2(5) //
}
val fun3 = (z: Int) => fun1(z + 2)
fun3(3) // 25
def matcher(l: List[Int]): Int = l match {
  case List(1, 2) => 1
  case List(2, 3) => 2
  case _          => 0
}



val l = for {
    i <- List(1, 2, 3, 4)
    if (i > 1)
  } yield i // List(2, 3, 4)

        l = [1, 2, 3, 4].find_all {|i| i > 1}

        l = [i for i in (1, 2, 3, 4) if (i > 1)]
object Application {
  def main(args: Array[String]) {
    println(”Hello, ” + args(0))
  }
}




 scalac
  $ scalac Application.scala

                 scala
  $ scala -cp . Application
object Application {
  def main(args: Array[String]) {
    println(”Hello, ” + args(0))
  }
}

 def
               :   ,    :    , ...

                             +
          Array[         ]
               []                ()
object Application {
    def main(args: Array[String]) {
      println(”Hello, ” + args(0))
    }
  }

object
class
println
‣ object
  class



                  object


    final class Application$cls
    private var Application$instance = null
    final def Application = {
      if (Application$instance == null)
        Application$instance = new Application$cls
      return Application$instance
    }
‣ println
                 object




    import Scala.Predef._
123 0x123 0123 456L
    123.0 13e-8 5e-35D
       true false
    ’A’ ’   ’ ’u0041’
     ”howdyn” ””ahoy””

”””I think ”Scala” is great”””
      (1, 2, 3)
    <foo>bar</foo>
val           var
      var val         :   =


val
val str: String = ”hey”
val i = 123 //
val f = 5.0
val longstr = ”””test”test”””
val tuple = (1, 2, 3)
val xml =
  <property>
    <name>prop</name>
    <value>{longstr}{tuple(0)}</value>
  </property>
Any

        AnyVal                            AnyRef

Unit                         ScalaObject        Java

Boolean    Char

 Byte     Short              ...   ...

 Int       Long              ...   ...

Float     Double             ...   ...


                                         Null

                   Nothing
asInstanceOf[   ]




isInstanceOf[   ]
class           {
}
class           extends                     {
}
class           extends
                 with               ... {
}
private class              ... {}
protected class              ... {}
sealed class              ... {}
abstract class              ... {}
final class             ... {}
object                  {
}
object                  extends              {
}
object                  extends
                 with             ... {
}
private object                    ... {}
protected object                    ... {}
trait             {
}
trait             extends
                with                 ... {
}
trait             extends
                with                 ... {
}
private trait                ... {}
protected trait                ... {}
sealed trait                ... {}
public protected
private sealed
 sealed




          abstract
class         (             ) {
    val      =
    var      =
    protected val|var ...
    private val|var ...
    def this ...
    def
    private def ...
    protected def ...
}
def   (           ) =
def   (           ):           =
def   (           ) {...}

          :   ,         :   , ...
class Foo {
  private var prop_: Int = 0
  def prop = prop_
  def prop_=(value: Int) = { prop_ = value }
}

                   _=



  val f: Foo = new Foo
  f.prop = 123 // prop_=()
def this
class Foo {
  def this(i: Int) = {
    this()
    ...          ...
    }
}

class Bar(param1: Double) {
  val param1sq = param1 * param1
  def this(strParam: String) = {
    this(strParam.toDouble)
  }
}
trait Named {
  private var name_ = quot;quot;
  def name = name_
  def name_=(v: String) = { name_ = v }
}

class Person(firstName: String,
             lastName: String)
      extends AnyRef with Named {
  name = firstName + quot; quot; + lastName
}

trait   SuperMonkeys {
  val   reina = new Person(quot;Reinaquot;, quot;Miyauchiquot;)
  val   lina = new Person(quot;Ritsukoquot;, quot;Matsudaquot;)
  val   mina = new Person(quot;Minakoquot;, quot;Amahisaquot;)
  val   nana = new Person(quot;Nanakoquot;, quot;Takushiquot;)
}

//   extends
class            with SuperMonkeys {
}
[       ,       ...]




    [       ,    ...]
class MyArrayList[T] {
  private var elems_ = new Array[T](1)
  private var size_ = 0
  def size = size_
  def get(index: Int): T = {
    if (index < 0 || index >= size_)
      throw new IndexOutOfBoundsException()
    elems_(index)
  }
  def append(elem: T): Unit = {
    if (size_ >= elems_.length) {
      val newElems = new Array[T](elems_.length * 2)
      Array.copy(elems_, 0, newElems, 0, elems_.length)
      elems_ = newElems
    }
    elems_(size_) = elem
    size_ += 1                var mal = MyArrayList[String]()
  }                           mal.append(”hoge”)
}                             mal.append(”fuga”)
                              println(mal.get(0)) // hoge
                              println(mal.get(1)) // fuga
match {
    case       =>
    case       =>
    case       =>
}
case class


             _
class Card {}

trait Colored {
  val color: String
}

case class NumberedCard(color: String,
                        number: Int)
     extends Card with Colored {}

case class WildCard extends Card {}

case class DrawTwo(color: String)
     extends Card with Colored {}

case class DrawFour extends Card {}

def putCard = this.discarded match {
  case NumberedCard(color, number) => 1
  case WildCard(color) => 2
  case DrawTwo(color) => 3
  case DrawFour(color) => 4
}
for (   <- Iterable) {
  ...    ...
}
for (a <- (1, 2, 3, 4)) {
  println(a)
}

//
for (a <- (1, 2, 3, 4);
     b <- (1, 2, 3, 4)) {
  println(a)
  println(b)
}
var result = List[Int]()
for (i <- List(1, 2, 3, 4)) {
  result += (i * i)
}



   val result = for (i <- List(1, 2, 3, 4))
                yield i * i
val (a, b, c) = (1, 2, 3)




var l = List(1, 2, 3) // val
l += 4
println(l) // 1, 2, 3, 4



import scala.collection.mutable._
val l = new ListBuffer[Int]()
l ++= List(1, 2, 3, 4)
l += 5
println(l) // 1, 2, 3, 4, 5
var dict = Map(
   (”apple”, 100),
   (”microsoft”, 200),
   (”banana”, 300)
)
dict -= ”microsoft”
// ”apple” -> 100, ”banana” -> 300
println(dict)
Java and Scala Hello World Examples

More Related Content

What's hot

Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteDirkjan Bussink
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021Jorge Vásquez
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksSeniorDevOnly
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Scala jeff
Scala jeffScala jeff
Scala jeffjeff kit
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritanceshatha00
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - IntroDavid Copeland
 

What's hot (20)

Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of Twente
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Scala jeff
Scala jeffScala jeff
Scala jeff
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 
C h 04 oop_inheritance
C h 04 oop_inheritanceC h 04 oop_inheritance
C h 04 oop_inheritance
 
Grammarware Memes
Grammarware MemesGrammarware Memes
Grammarware Memes
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
All about scala
All about scalaAll about scala
All about scala
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - Intro
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 

Viewers also liked

Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingDebasish Ghosh
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Tomer Gabel
 
Functional Programming For All - Scala Matsuri 2016
Functional Programming For All - Scala Matsuri 2016Functional Programming For All - Scala Matsuri 2016
Functional Programming For All - Scala Matsuri 2016Zachary Abbott
 
Contributing to Scala OSS from East Asia #ScalaMatsuri
 Contributing to Scala OSS from East Asia #ScalaMatsuri Contributing to Scala OSS from East Asia #ScalaMatsuri
Contributing to Scala OSS from East Asia #ScalaMatsuriKazuhiro Sera
 
Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Yukishige Nakajo
 
あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)x1 ichi
 
こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門tanacasino
 

Viewers also liked (8)

Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain Modeling
 
ScalaMatsuri 2016
ScalaMatsuri 2016ScalaMatsuri 2016
ScalaMatsuri 2016
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)
 
Functional Programming For All - Scala Matsuri 2016
Functional Programming For All - Scala Matsuri 2016Functional Programming For All - Scala Matsuri 2016
Functional Programming For All - Scala Matsuri 2016
 
Contributing to Scala OSS from East Asia #ScalaMatsuri
 Contributing to Scala OSS from East Asia #ScalaMatsuri Contributing to Scala OSS from East Asia #ScalaMatsuri
Contributing to Scala OSS from East Asia #ScalaMatsuri
 
Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由Rubyからscalaに変えるべき15の理由
Rubyからscalaに変えるべき15の理由
 
あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)あなたのScalaを爆速にする7つの方法(日本語版)
あなたのScalaを爆速にする7つの方法(日本語版)
 
こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門こわくないよ❤️ Playframeworkソースコードリーディング入門
こわくないよ❤️ Playframeworkソースコードリーディング入門
 

Similar to Java and Scala Hello World Examples

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
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 2Kirill Rozov
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala LanguageAshal aka JOKER
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basicswpgreenway
 
(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
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_onefuturespective
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmerstymon Tobolski
 

Similar to Java and Scala Hello World Examples (20)

Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
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
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Scala
ScalaScala
Scala
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to 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?
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Meet scala
Meet scalaMeet scala
Meet scala
 

More from bpstudy

DXとプロセスマイニング part02
DXとプロセスマイニング part02DXとプロセスマイニング part02
DXとプロセスマイニング part02bpstudy
 
DXとプロセスマイニング Part01
DXとプロセスマイニング Part01DXとプロセスマイニング Part01
DXとプロセスマイニング Part01bpstudy
 
What is Ethereum?
What is Ethereum?What is Ethereum?
What is Ethereum?bpstudy
 
アプリケーションアーキテクチャの現在、過去、未来
アプリケーションアーキテクチャの現在、過去、未来アプリケーションアーキテクチャの現在、過去、未来
アプリケーションアーキテクチャの現在、過去、未来bpstudy
 
ファン上がりのフリーライター。そのこれまでとこれから
ファン上がりのフリーライター。そのこれまでとこれからファン上がりのフリーライター。そのこれまでとこれから
ファン上がりのフリーライター。そのこれまでとこれからbpstudy
 
エンジニアのためのお金の話
エンジニアのためのお金の話エンジニアのためのお金の話
エンジニアのためのお金の話bpstudy
 
ダルビッシュ有のツイッターとカープ女子ブームとプロ野球革命!
ダルビッシュ有のツイッターとカープ女子ブームとプロ野球革命!ダルビッシュ有のツイッターとカープ女子ブームとプロ野球革命!
ダルビッシュ有のツイッターとカープ女子ブームとプロ野球革命!bpstudy
 
価値のデザイン
価値のデザイン価値のデザイン
価値のデザインbpstudy
 
モデリングの神髄
モデリングの神髄モデリングの神髄
モデリングの神髄bpstudy
 
開発者としての心
開発者としての心開発者としての心
開発者としての心bpstudy
 
新たな価値観への経営視点の転換
新たな価値観への経営視点の転換新たな価値観への経営視点の転換
新たな価値観への経営視点の転換bpstudy
 
hbqpbp study Skype-Bot Centric Development
hbqpbp study Skype-Bot Centric Developmenthbqpbp study Skype-Bot Centric Development
hbqpbp study Skype-Bot Centric Developmentbpstudy
 
BPStudy#50 BPStudy
BPStudy#50 BPStudyBPStudy#50 BPStudy
BPStudy#50 BPStudybpstudy
 
Be cloud
Be cloudBe cloud
Be cloudbpstudy
 
俺の経営論(BP2010)
俺の経営論(BP2010)俺の経営論(BP2010)
俺の経営論(BP2010)bpstudy
 
Bpstudy #37 djagno tips
Bpstudy #37 djagno tipsBpstudy #37 djagno tips
Bpstudy #37 djagno tipsbpstudy
 
BPStudy#36 beproud-bot
BPStudy#36 beproud-botBPStudy#36 beproud-bot
BPStudy#36 beproud-botbpstudy
 
GNU screen (vim study #1)
GNU screen (vim study #1)GNU screen (vim study #1)
GNU screen (vim study #1)bpstudy
 
vim入門 (vim study #1)
vim入門 (vim study #1)vim入門 (vim study #1)
vim入門 (vim study #1)bpstudy
 

More from bpstudy (19)

DXとプロセスマイニング part02
DXとプロセスマイニング part02DXとプロセスマイニング part02
DXとプロセスマイニング part02
 
DXとプロセスマイニング Part01
DXとプロセスマイニング Part01DXとプロセスマイニング Part01
DXとプロセスマイニング Part01
 
What is Ethereum?
What is Ethereum?What is Ethereum?
What is Ethereum?
 
アプリケーションアーキテクチャの現在、過去、未来
アプリケーションアーキテクチャの現在、過去、未来アプリケーションアーキテクチャの現在、過去、未来
アプリケーションアーキテクチャの現在、過去、未来
 
ファン上がりのフリーライター。そのこれまでとこれから
ファン上がりのフリーライター。そのこれまでとこれからファン上がりのフリーライター。そのこれまでとこれから
ファン上がりのフリーライター。そのこれまでとこれから
 
エンジニアのためのお金の話
エンジニアのためのお金の話エンジニアのためのお金の話
エンジニアのためのお金の話
 
ダルビッシュ有のツイッターとカープ女子ブームとプロ野球革命!
ダルビッシュ有のツイッターとカープ女子ブームとプロ野球革命!ダルビッシュ有のツイッターとカープ女子ブームとプロ野球革命!
ダルビッシュ有のツイッターとカープ女子ブームとプロ野球革命!
 
価値のデザイン
価値のデザイン価値のデザイン
価値のデザイン
 
モデリングの神髄
モデリングの神髄モデリングの神髄
モデリングの神髄
 
開発者としての心
開発者としての心開発者としての心
開発者としての心
 
新たな価値観への経営視点の転換
新たな価値観への経営視点の転換新たな価値観への経営視点の転換
新たな価値観への経営視点の転換
 
hbqpbp study Skype-Bot Centric Development
hbqpbp study Skype-Bot Centric Developmenthbqpbp study Skype-Bot Centric Development
hbqpbp study Skype-Bot Centric Development
 
BPStudy#50 BPStudy
BPStudy#50 BPStudyBPStudy#50 BPStudy
BPStudy#50 BPStudy
 
Be cloud
Be cloudBe cloud
Be cloud
 
俺の経営論(BP2010)
俺の経営論(BP2010)俺の経営論(BP2010)
俺の経営論(BP2010)
 
Bpstudy #37 djagno tips
Bpstudy #37 djagno tipsBpstudy #37 djagno tips
Bpstudy #37 djagno tips
 
BPStudy#36 beproud-bot
BPStudy#36 beproud-botBPStudy#36 beproud-bot
BPStudy#36 beproud-bot
 
GNU screen (vim study #1)
GNU screen (vim study #1)GNU screen (vim study #1)
GNU screen (vim study #1)
 
vim入門 (vim study #1)
vim入門 (vim study #1)vim入門 (vim study #1)
vim入門 (vim study #1)
 

Java and Scala Hello World Examples

  • 2.
  • 3.
  • 4. Java 1.5 Pizza GJ Scala Funnel
  • 5.
  • 6.
  • 7. public class Application { public static void main(String[] args) { System.out.println(”Hello, World”); } } object Application { def main(args: Array[String]) { println(”Hello, World”) } }
  • 8. // val numbers = 1.until(10) // 1, 2, ..., 10 println(numbers(5)) // ”6” // println((5).+(3)) // ”8” println(5 + 3) // ”()” ”.” println(5.+(3)) // 5.0+(3) // println(1 until 10)
  • 9. // // (?)
  • 10. // String Unit // println puts val puts: String => Unit = println puts(”hey!”) def fun1(x: Int): Int = { def fun2(y: Int): Int = x * y fun2(5) // } val fun3 = (z: Int) => fun1(z + 2) fun3(3) // 25
  • 11. def matcher(l: List[Int]): Int = l match { case List(1, 2) => 1 case List(2, 3) => 2 case _ => 0 } val l = for { i <- List(1, 2, 3, 4) if (i > 1) } yield i // List(2, 3, 4) l = [1, 2, 3, 4].find_all {|i| i > 1} l = [i for i in (1, 2, 3, 4) if (i > 1)]
  • 12.
  • 13. object Application { def main(args: Array[String]) { println(”Hello, ” + args(0)) } } scalac $ scalac Application.scala scala $ scala -cp . Application
  • 14. object Application { def main(args: Array[String]) { println(”Hello, ” + args(0)) } } def : , : , ... + Array[ ] [] ()
  • 15. object Application { def main(args: Array[String]) { println(”Hello, ” + args(0)) } } object class println
  • 16. ‣ object class object final class Application$cls private var Application$instance = null final def Application = { if (Application$instance == null) Application$instance = new Application$cls return Application$instance }
  • 17. ‣ println object import Scala.Predef._
  • 18.
  • 19. 123 0x123 0123 456L 123.0 13e-8 5e-35D true false ’A’ ’ ’ ’u0041’ ”howdyn” ””ahoy”” ”””I think ”Scala” is great””” (1, 2, 3) <foo>bar</foo>
  • 20. val var var val : = val
  • 21. val str: String = ”hey” val i = 123 // val f = 5.0 val longstr = ”””test”test””” val tuple = (1, 2, 3) val xml = <property> <name>prop</name> <value>{longstr}{tuple(0)}</value> </property>
  • 22.
  • 23. Any AnyVal AnyRef Unit ScalaObject Java Boolean Char Byte Short ... ... Int Long ... ... Float Double ... ... Null Nothing
  • 24. asInstanceOf[ ] isInstanceOf[ ]
  • 25. class { } class extends { } class extends with ... { } private class ... {} protected class ... {} sealed class ... {} abstract class ... {} final class ... {}
  • 26. object { } object extends { } object extends with ... { } private object ... {} protected object ... {}
  • 27. trait { } trait extends with ... { } trait extends with ... { } private trait ... {} protected trait ... {} sealed trait ... {}
  • 28.
  • 30. class ( ) { val = var = protected val|var ... private val|var ... def this ... def private def ... protected def ... }
  • 31. def ( ) = def ( ): = def ( ) {...} : , : , ...
  • 32. class Foo { private var prop_: Int = 0 def prop = prop_ def prop_=(value: Int) = { prop_ = value } } _= val f: Foo = new Foo f.prop = 123 // prop_=()
  • 33.
  • 35. class Foo { def this(i: Int) = { this() ... ... } } class Bar(param1: Double) { val param1sq = param1 * param1 def this(strParam: String) = { this(strParam.toDouble) } }
  • 36. trait Named { private var name_ = quot;quot; def name = name_ def name_=(v: String) = { name_ = v } } class Person(firstName: String, lastName: String) extends AnyRef with Named { name = firstName + quot; quot; + lastName } trait SuperMonkeys { val reina = new Person(quot;Reinaquot;, quot;Miyauchiquot;) val lina = new Person(quot;Ritsukoquot;, quot;Matsudaquot;) val mina = new Person(quot;Minakoquot;, quot;Amahisaquot;) val nana = new Person(quot;Nanakoquot;, quot;Takushiquot;) } // extends class with SuperMonkeys { }
  • 37.
  • 38. [ , ...] [ , ...]
  • 39. class MyArrayList[T] { private var elems_ = new Array[T](1) private var size_ = 0 def size = size_ def get(index: Int): T = { if (index < 0 || index >= size_) throw new IndexOutOfBoundsException() elems_(index) } def append(elem: T): Unit = { if (size_ >= elems_.length) { val newElems = new Array[T](elems_.length * 2) Array.copy(elems_, 0, newElems, 0, elems_.length) elems_ = newElems } elems_(size_) = elem size_ += 1 var mal = MyArrayList[String]() } mal.append(”hoge”) } mal.append(”fuga”) println(mal.get(0)) // hoge println(mal.get(1)) // fuga
  • 40. match { case => case => case => }
  • 42. class Card {} trait Colored { val color: String } case class NumberedCard(color: String, number: Int) extends Card with Colored {} case class WildCard extends Card {} case class DrawTwo(color: String) extends Card with Colored {} case class DrawFour extends Card {} def putCard = this.discarded match { case NumberedCard(color, number) => 1 case WildCard(color) => 2 case DrawTwo(color) => 3 case DrawFour(color) => 4 }
  • 43. for ( <- Iterable) { ... ... }
  • 44. for (a <- (1, 2, 3, 4)) { println(a) } // for (a <- (1, 2, 3, 4); b <- (1, 2, 3, 4)) { println(a) println(b) }
  • 45. var result = List[Int]() for (i <- List(1, 2, 3, 4)) { result += (i * i) } val result = for (i <- List(1, 2, 3, 4)) yield i * i
  • 46.
  • 47.
  • 48.
  • 49. val (a, b, c) = (1, 2, 3) var l = List(1, 2, 3) // val l += 4 println(l) // 1, 2, 3, 4 import scala.collection.mutable._ val l = new ListBuffer[Int]() l ++= List(1, 2, 3, 4) l += 5 println(l) // 1, 2, 3, 4, 5
  • 50.
  • 51.
  • 52. var dict = Map( (”apple”, 100), (”microsoft”, 200), (”banana”, 300) ) dict -= ”microsoft” // ”apple” -> 100, ”banana” -> 300 println(dict)