Copyright © Cay S. Horstmann 2015
This work is licensed under a Creative Commons Attribution 4.0 International License
&&
, ||
if (i < s.length && s(i) == '.')
def and(a: Boolean, b: Boolean) = if (!a) false else b
val s = "Hello" val i = 5 if (and(i < s.length, s(i) == '.')) // Throws IndexOutOfBoundsException
def
) is prefixed by =>
, it is not evaluated when the function is called.
def and(a: => Boolean, b: => Boolean) = if (!a) false else b
and(i < s.length, s(i) == '.')
and
receives two functions () => { i < s.length }
, () => { s(i) == '.' }
a
and b
are evaluated, the functions are called
if (!a) ... // Calls () => { i < s.length }
Which of these will work? We want to call
ifElse(i < 5, println("Hi"), println("Bye"))
def ifElse(c: Boolean, a: Unit, b: Unit) { c && { a; true } || { b; true } }
def ifElse(c: Boolean, a: => Unit, b: => Unit) { c && { a; true } || { b; true } }
def ifElse(c: => Boolean, a: => Unit, b: => Unit) { c && { a; true } || { b; true } }
lazy val
val
is declared lazy
, its initialization is deferred until the first time it is used.
lazy val words = scala.io.Source.fromFile("/usr/share/dict/words").mkString // Evaluated the first time words is used
words
is never used, the file is not opened.val
and def
:
val words = scala.io.Source.fromFile("/usr/share/dict/words").mkString // Evaluated as soon as words is defined def words = scala.io.Source.fromFile("/usr/share/dict/words").mkString // Evaluated every time words is used
words
is usedwhile
while
. We have two arguments, the condition and the body. For example,
val iter = Source.fromFile("/usr/share/dict/words").getLines.buffered // "buffered" gives you an iterator with a "head" method for lookahead While(iter.head.length < 15, iter.next) val longWord = iter.head // The first word of length >= 15How do you declare
While
? (Just the header, not the implementation.)
While(iter.head.length < 15) { iter.next }Hint: Curry
Do this as individual work, not with your partner
When all done, email the signed zip files to Fatemeh.Borran@heig-vd.ch