The functional style of programming is that methods should not have side effects.
A method's only act should be to compute and return a value.
- less entangled
- more reliable
- reusable
Applying this functional philosophy to the world of objects means making objects immutable.
Scala Lists are always immutable(whereas Java Lists can be mutable).
More generally, Scala's List is designed to enable a functional style of programming.
val onTwoThress = List(1,2,3)
val onTwo = List(1,2)
val threeFour = List(3,4)
val oneTwoThreeFour = oneTwo ::: threeFour
println(oneTwo + " and " + threeFour + " were not mutated.")
println("Thus, "+ onTwoThreeFour + " is a new list.")
If you run this script, you'll see:
List(1,2) and List(3,4) were not mutated.
Thus, List(1,2,3,4) is a new List.
List has method named ':::' for list concatenation.
'::' is pronounced "cpns."
Cons prepends a new element to the beginning of an existiong list, and returns the resulting list.
val thwThree = List(2,3)
val oneTwoThree = 1 :: twoThree
println(oneTwoThree)
You'll see:
List(1,2,3)
댓글 없음:
댓글 쓰기