a = 1 (값이 있음), a = null (값이 없음)
a = Some(1) (값이 있음), a = None (값이 없음)
val a = 1
a: Int = 1
var a = 1
// scala는 a에 null을 대입할 수 없음.
a = null
cmd1.sc:3: an expression of type Null is ineligible for implicit conversion val res1_1 = a = null ^
Compilation Failed
val a = Some(1)
// if(a.isEmpty) null else a.get + 1 안좋은 코드 예시
a.map(_ + 1)
a: Some[Int] = Some(1) res1_1: Option[Int] = Some(2)
a.getOrElse(-1)
res2: Int = 1
val a = None
a: None.type = None
val list = List(1, 2, 3, 4)
list.filter((x: Int) => x < 3)
val testNumber1 = (x: Int) => x < 3 // function as a 1st-class object! list.filter(testNumber1)
list.filter((x) => x < 3) // target typing
list.filter(x => x < 3)
list.filter(_ < 3) // placeholder
def testNumber2(x: Int) = x < 3 // function
list.filter(x => testNumber2(x))
list.filter(testNumber2(_))
list.filter(testNumber2 _)
list.filter(testNumber2)
list: List[Int] = List(1, 2, 3, 4) res4_1: List[Int] = List(1, 2) testNumber1: Int => Boolean = <function1> res4_3: List[Int] = List(1, 2) res4_4: List[Int] = List(1, 2) res4_5: List[Int] = List(1, 2) defined function testNumber2 res4_7: List[Int] = List(1, 2) res4_8: List[Int] = List(1, 2) res4_9: List[Int] = List(1, 2) res4_10: List[Int] = List(1, 2)
• Java의 switch ~ case 와 비슷하지만, 훨씬 강력한 도구
val a = List((1,(0,4)), (2,(0,5)))
a: List[(Int, (Int, Int))] = List((1, (0, 4)), (2, (0, 5)))
a.map(_._2._2) foreach println // 튜플의 key의 right 원소를 뽑고 싶음. 보기 불편함.
4 5
a.map{case(key,(left,right)) => right} foreach println
4 5
implicit def stringToInt(number: String): Int = {
number match {
case "one" => 1
case "two" => 2
}
}
def printNumber(n: Int) = println(n)
printNumber("one")
1
defined function stringToInt defined function printNumber
더 직관적이고 일관성 있는 코드를 만들 수 있다!
DateParser.parse("2017-07-29") // java style
"2017-07-29".toDateTime // better solution using implicit conversion
object DateParser {
def parse(dateString :String) = new java.util.Date
}
DateParser.parse("2017-07-29")
class DateConverter(val s: String) {
def toDateTime = DateParser.parse(s)
}
implicit def string2DateConverter(s: String) = new DateConverter(s)
"2017-07-29".toDateTime
res9_0: java.util.Date = Tue May 29 20:47:26 KST 2018 res9_1: java.util.Date = Tue May 29 20:47:26 KST 2018 defined object DateParser res9_3: java.util.Date = Tue May 29 20:47:26 KST 2018 defined class DateConverter defined function string2DateConverter res9_6: java.util.Date = Tue May 29 20:47:26 KST 2018