Fahad/CodeSamples/ExtractorObjects.scala
author Christian Urban <christian dot urban at kcl dot ac dot uk>
Wed, 24 Aug 2016 11:30:46 +0100
changeset 209 c592ea0661ae
parent 44 a751aa1ee4f7
permissions -rw-r--r--
updated
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
44
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     1
package Main
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     2
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     3
object Twice {
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     4
  def apply(x: Int): Int = x * 2
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     5
  def unapply(z: Int): Option[Int] = if (z % 2 == 0) Some(z / 2) else None
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     6
}
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     7
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     8
object TwiceTest extends App {
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
     9
  val x = Twice(10)
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    10
  x match { case Twice(n) => Console.println(n) } //prints 21
a751aa1ee4f7 Code Samples
Fahad Ausaf <fahad.ausaf@kcl.ac.uk>
parents:
diff changeset
    11
}