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

Why these two code's behavior different?

1 reply
SXPCrazy
Joined: 2010-06-12,
User offline. Last seen 1 year 38 weeks ago.
I compilation these two code below, but the first one no error and the other one had.
def t1(a: (Int) => Unit) { t2(a) }
def t2(a: => Unit) { a println(a) }
t1 { x => println("run") 1 }
===============> code 2
def t1(a: (Int) => Int) { t2(a) }
def t2(a: => Int) { a println(a) }
t1 { x => println("run") 1}
when compilation above code, generate these error:
error: type mismatch; found   : (Int) => Intrequired: Intt2(a)
what is the different statement meaning? why first one can run without error?

Alefas
Joined: 2009-06-23,
User offline. Last seen 33 weeks 5 days ago.
RE: Why these two code's behavior different?

It’s because Unit Value Discarding.

Any type can be treated as unit type (It’s not type conformance, it’s like implicit conversion). So compiler processes this code in such way:

 

def t1(a: (Int) => Unit) {

            t2({a; ()})

}

 

def t2(a: => Unit) {

            a

            println(a)

}

 

t1 {

            x =>

            println("run")

            1

}

 

On the other hand there is no conversion form type (Int) => Int to Int. So it’s compiler error.

 

Best regards,

Alexander Podkhalyuzin.

 

 

From: SXPCrazy [mailto:sxpcrazy@gmail.com]
Sent: Monday, July 26, 2010 12:57 PM
To: scala-user@listes.epfl.ch
Subject: [scala-user] Why these two code's behavior different?

 

I compilation these two code below, but the first one no error and the other one had.

 

def t1(a: (Int) => Unit) {

            t2(a)

}

 

def t2(a: => Unit) {

            a

            println(a)

}

 

t1 {

            x =>

            println("run")

            1

}

 

===============> code 2

 

def t1(a: (Int) => Int) {

            t2(a)

}

 

def t2(a: => Int) {

            a

            println(a)

}

 

t1 {

            x =>

            println("run")

            1

}

 

when compilation above code, generate these error:

 

error: type mismatch;

found   : (Int) => Int

required: Int

t2(a)

 

what is the different statement meaning? why first one can run without error?

 

 

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