読者です 読者をやめる 読者になる 読者になる

落書きノート

ふと自分が気になった事を書いてます

Scala シングルトンオブジェクト等々

なかなか難しいですが、色々プログラムを作っていたりすると馴染みのある表現が出てきます。言語経験が豊富な人にはわかりやすいかもしれません。

Welcome to Scala version 2.11.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Programmer(_language: String){
     | println("Programmerインスタンスを生成します")
     | println("language = " + _language)
     | require(_language != null)
     | var language = _language
     | def this() = this("Scala")
     | def coding() = println(language + "を使ってコーディングします")
     | }
defined class Programmer

scala> val pg = new Programmer
Programmerインスタンスを生成します
language = Scala
pg: Programmer = Programmer@1a407d53

scala> val pg = new Programmer(null)
Programmerインスタンスを生成します
language = null
java.lang.IllegalArgumentException: requirement failed
  at scala.Predef$.require(Predef.scala:207)
  ... 34 elided

scala> class Sample{
     | def add(x:Int, y:Int) = x + y
     | def add(x:Double, y:Double) = x + y
     | def add(x:Int, y:Int, z:Int) = x + y + z
     | }
defined class Sample

scala> val s = new Sample
s: Sample = Sample@cb644e

scala> s.add(1,2)
res0: Int = 3

scala> s.add(1D,2D)
res1: Double = 3.0

scala> s.add(1,2,3)
res2: Int = 6

scala> object SampleUtil{
     | def hello() = println("hello")
     | }
defined object SampleUtil

scala> SampleUtil.hello()
hello

scala> :paste
// Entering paste mode (ctrl-D to finish)

class SampleCompanion private (num:Int)

object SampleCompanion {
  def apply(num:Int) = {
    new SampleCompanion(num)
  }
}

object Main {
  def main(args: Array[String]) = {
    val ins = SampleCompanion(10)
    println(ins)
  }
}

// Exiting paste mode, now interpreting.

defined class SampleCompanion
defined object SampleCompanion
defined object Main

scala> SampleCompanion(10)
res4: SampleCompanion = SampleCompanion@25359ed8

scala> val ins = SampleCompanion(10)
ins: SampleCompanion = SampleCompanion@1dd92fe2

scala> println(ins)
$line17.$read$$iw$$iw$SampleCompanion@1dd92fe2

scala> val m = Map("Scala"->1, "Java"->2)
m: scala.collection.immutable.Map[String,Int] = Map(Scala -> 1, Java -> 2)

scala> m.get("Scala")
res6: Option[Int] = Some(1)

scala> m.get("Ruby")
res7: Option[Int] = None

scala> m.get("Java")
res8: Option[Int] = Some(2)

scala> m.get("Scala").get
res9: Int = 1

scala> m.get("Ruby").get
java.util.NoSuchElementException: None.get
  at scala.None$.get(Option.scala:347)
  at scala.None$.get(Option.scala:345)
  ... 33 elided

scala> m.get("Ruby").getOrElse("nothing!")
res11: Any = nothing!

scala> def testMatch(opt:Option[Int]) = {
     | opt match {
     | case Some(n) => println(n)
     | case None => println("None!")
     | }
     | }
testMatch: (opt: Option[Int])Unit

scala> testMatch(Some(10))
10

scala> testMatch(None)
None!

scala> def testMatch(opt:Option[Int]) = {
     | opt match {
     | case Some(a) => println(a)
     | case None => println("None!")
     | }
     | }
testMatch: (opt: Option[Int])Unit

scala> testMatch(Some(20))
20

scala> testMatch(None)
None!

scala> class Apple
defined class Apple

scala> object Apple{
     | def unapply(a: Any): Boolean = {
     | if(a.isInstanceOf[Apple]) true else false
     | }
     | }
defined object Apple
warning: previously defined class Apple is not a companion to object Apple.
Companions must be defined together; you may wish to use :paste mode for this.

scala> class Orange(val name:String)
defined class Orange

scala> object Orange{
     | def apply(name:String): Orange = new Orange(name)
     | def unapply(a: Orange):Option[String] = Some(a.name)
     | }
defined object Orange
warning: previously defined class Orange is not a companion to object Orange.
Companions must be defined together; you may wish to use :paste mode for this.

scala> val ap = new Apple
ap: Apple = Apple@700f518a

scala> Apple.unapply(ap)
res17: Boolean = true

scala> val ap2 = new Orange("test")
ap2: Orange = Orange@5bc7e78e

scala> Apple.unapply(ap2)
res18: Boolean = false

scala> val ap = Orange.apply("test")
ap: Orange = Orange@68a4dcc6

scala> Orange.unapply(ap)
res19: Option[String] = Some(test)

scala> val ap = Orange.apply("10")
ap: Orange = Orange@37df14d1

scala> Orange.unapply(ap)
res20: Option[String] = Some(10)

scala> def matchTest(value: Any) = {
     | value match {
     | case Apple => println("Apple")
     | case Orange("DEKOPON") => println("Orange.name = DEKOPON")
     | case _ => println("other")
     | }
     | }
matchTest: (value: Any)Unit

scala> matchTest(Orange("something"))
other

scala> matchTest(Orange("DEKOPON"))
Orange.name = DEKOPON

scala> matchTest(Apple)
Apple

scala> matchTest("hello")
other

scala> case Orange(name) => println("Orange.name=" + name)
<console>:1: error: illegal start of definition
       case Orange(name) => println("Orange.name=" + name)
       ^

scala> sys.exit