This page is no longer maintained — Please continue to the home page at www.scala-lang.org

{} is not what I thought !?!

1 reply
Razvan Cojocaru 2
Joined: 2009-11-20,
User offline. Last seen 42 years 45 weeks ago.

in the example below, the result is "1start2" while I thought it should be
start12. Apparently, the
{} runs the first statement and returns the second statement as a function
and that's what the implicit wf is applied to...

... counter-intuitive. Is this a bug ... obviously, but is it a scala bug or
of my faulty right brain ?

you can play with the code online here: http://bit.ly/bHsfwo
http://bit.ly/bHsfwo


// 1.select the object and run selection
object ScaBug1 {
var acc = ""

case class C1 (val f:() =>Unit) {
def doit () = f()
}

def wif (c: =>Boolean) (t:C1) = t
implicit def wf (f : => Unit) = C1 (()=>f)

val d = wif (1==1) {
acc += "1"
acc += "2"
}

def doit : String = { acc += "start"; d.doit(); acc}
}

// 2. run line below
ScaBug1.doit

-----
Razvan Cojocaru,
Work: http://www.sigma-systems.com
Playground: http://wiki.homecloud.ca
Latest cool toy: http://scripster.razie.com
Follow me: http://feeds.razie.com/RazvanTech RSS Feed ,
http://twitter.com/razie Twitter , http://github.com/razie GitHub .

Razvan Cojocaru 2
Joined: 2009-11-20,
User offline. Last seen 42 years 45 weeks ago.
Re: {} is not what I thought !?!

I.e. I kind'a see what's going on, but it's still freaky for me...thinking
out loud below :)

scala> val f = { println("1"); println("2")}
1
2
f: Unit = ()

scala>

--------------------

scala> val f = () => { println("1"); println("2")}
f: () => Unit =

scala>

-------------------

scala> List(1,2).foreach {println(_)}
1
2

scala>

--------------------

scala> def repeat (f: =>Unit) { f;f;f}
repeat: (f: => Unit)Unit

scala> repeat { println("yuhu.")}
yuhu.
yuhu.
yuhu.

scala>

----------------------

scala> case class C(f: =>Unit)
:1: error: `val' parameters may not be call-by-name
case class C(f: =>Unit)
^

----------------------

scala> case class C(f: () => Unit)
defined class C

scala> implicit def wf (f: =>Unit) = C(()=>f)
wf: (f: => Unit)C

scala> def repeat2 (c:C) {c.f;c.f;c.f}
repeat2: (c: C)Unit

scala> repeat2 {println("1"); println("2")}
1

scala>

----------------------

I guess you see my (faulty) reasoning...but....

-----
Razvan Cojocaru,
Work: http://www.sigma-systems.com
Playground: http://wiki.homecloud.ca
Latest cool toy: http://scripster.razie.com
Follow me: http://feeds.razie.com/RazvanTech RSS Feed ,
http://twitter.com/razie Twitter , http://github.com/razie GitHub .

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland