My Journey in Scala, Part 1: Basic


classOf[XClass]
val b: Boolean = that.isInstanceOf[Date]
val o: Date = that.asInstanceOf[Date]
Thread sleep 1000
override def toString(): String = "xx"

No ternary operator in Scala, instead use an if/else expression:
abs = if (x >= 0) x else -x

String Interpolation
s"${someVariable} ${variable.field}"
f"" - format
raw"some\nAnotherline"

val sb = new StringBuilder

sb ++= "someThing"

Collections
Immutable
Mutable - scala.collection.mutable
ArrayBuffer
- Prepends and removes O(n)
val buf = new ArrayBuffer[Int]()
buf += 12


ListBuffer
- prepend and append O(1)

Convert scala collection to java collection
import collection.JavaConverters._
val m: java.util.Map[String, Int] = HashMap("abc" -> 1, "hello" -> 2).asJava

Exception handling
try {
} catch {
  case e: XException => somethin
}

Using Either
Spark ETL: Using Either to handle invalid data
try {
    Right(invalidValue)
  } catch {
    case e: Exception => Left(input)

}

Try{}
Success or Failure
if (result.isSuccess) result.get else defaultValue
result.getOrElse(defaultValue)

Main app
object Main extends App {}

import scala.util.{Left, Right}
import java.math.BigInteger, BigInteger._

Mystery of _
(1 to 10) map { _ * 2 }
(1 to 10).reduceLeft( _ + _ )

Unit - {}

Parallel collections
list.par.map(_ + 1)
Stream.iterate(startValue){i => i-10}.take(limit).foreach(println _)

for(i <- 1 until 5) - iterate 4 times

for(i <- 1 to 5)     - iterate 5 times

Check Scala version at runtime (for debug)
scala.util.Properties.versionString

Mix Java/Scala
Use scala-maven-plugin for mixed java/scala projects

Integrate with spring
http://hub.darcs.net/psnively/spring-scala

Autowire Java/Scala Bean
@Service
class Sevice{
   @Autowired val Repo: Repository = null;
}

@Configuration
class Config {
    @Bean def someBean =  {}
}

Resources

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)