scala(11)A Tour of Scala: Polymorphic Methods
Polymorphic Methods
Methods in Scala can be parameterized with both values and types.
value parameters are enclosed in a pair of parentheses.
type parameters are declared within a pair of brackets.
object PolyTest extends App {
def dup[T](x: T, n: Int): List[T] =
if (n == 0) {
Nil
} else {
x :: dup(x, n - 1)
}
println(dup[Int](3, 4))//List(3, 3, 3, 3)
println(dup[String]("three", 3))//List(three, three, three)
println(dup("three", 3))
}
Scala Option, Some and None idiom
We return Null or Object in java, Null stands for failure, Object stands for succeed.
In Scala, we can return Option, where the Option object is either:
1. An instance of the Scala Some class
2. An instance of the Scala None class
Both Some and None are both children of Option.
Here are the example of None, Some and Option
package com.sillycat.easyscala.start.tour.tour3
object OptionSomeNoneTest {
def toInt(in: String): Option[Int] = {
try {
Some(Integer.parseInt(in.trim()))
} catch {
case e: NumberFormatException => None
}
}
def main(args: Array[String]): Unit = {
toInt("100") match {
case Some(i) => println(i)
case None => println("That didn't work.")
} // 100
toInt("hello") match {
case Some(i) => println(i)
case None => println("That didn't work.")
} //That didn't work.
val bag = List("1", "2", "foo", "3", "bar")
valsum = bag.flatMap(toInt).sum //flatMap know how to handle with None, Option, Some
println(sum) //6
}
}
Regular Expression Patterns
…snip…
Sealed Classes
…snip…
Traits
Almost like interface, but Scala allows traits to be partially implemented. In contrast to classes, traits may not have constructor parameters.
The example of Traits will be
package com.sillycat.easyscala.start.tour.tour3
trait Similarity {
def isSimilar(x: Any): Boolean
def isNotSimilar(x: Any): Boolean = !isSimilar(x)
}
We only implemented the isNotSimilar in the trait, the class extends the trait needs to be implemented the isSimilar method.
The test trait class will be as follow:
package com.sillycat.easyscala.start.tour.tour3
class Point(xc:Int, yc: Int) extends Similarity{
var x: Int = xc
var y: Int = yc
def isSimilar(obj:Any):Boolean = {
obj.isInstanceOf[Point] &&
obj.asInstanceOf[Point].x == x
}
}
object TraitsTest extends App{
val p1 = new Point(2,3)
val p2 = new Point(2,4)
val p3 = new Point(3,3)
println(p1.isNotSimilar(p2)) //false
println(p1.isNotSimilar(p3)) // true
println(p1.isNotSimilar(3)) //true
}
Map & FlatMap
Map works by applying a function to each element in the list.
def main(args: Array[String]): Unit = {
val l1 = List(1,2,3,4,5)
var l2 = l1.map(x => x*2)
println(l1 + " " + l2)
var l3 = l1.map(x => f(x))
println(l1 + " " + l3)
}
def f(x: Int) = if(x > 2) Some(x) else None
flagMap works applying a function that returns a sequence for each element in the list, and flattening the results into the original list.
def g(v:Int) = List(v-1, v, v+1)
var l4 = l1.map(x => g(x))
//List(1, 2, 3, 4, 5)
//List(List(0, 1, 2), List(1, 2, 3), List(2, 3, 4), List(3, 4, 5), List(4, 5, 6))
println (l1 + " " + l4)
var l5 = l1.flatMap(x=>g(x))
//List(1, 2, 3, 4, 5)
//List(0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6)
println (l1 + " " + l5)
Option class will also consider as sequence that is either empty or has 1 item.
var l6 = l3.flatMap(x => x )
println (l3 + " " + l6)
//List(None,None,Some(3),Some(4),Some(5)) List(3,4,5)
References:
http://www.scala-lang.org/node/121
http://www.scala-lang.org/node/122
http://www.scala-lang.org/node/123
http://www.scala-lang.org/node/126
http://alvinalexander.com/scala/using-scala-option-some-none-idiom-function-java-null
http://www.brunton-spall.co.uk/post/2011/12/02/map-map-and-flatmap-in-scala/
http://richard.dallaway.com/in-praise-of-flatmap