- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Why these two code's behavior different?
Mon, 2010-07-26, 09:57
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?
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?
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?