Reputation: 39
I have this method
def example(something):something {
val c=List()
if(){
if(){
val a=List()
}
else{
val a=List()
}
}
//here a or b are not declared
c:::a
}
How to declare it and make it visible? I can not use var.
Upvotes: 1
Views: 562
Reputation: 24769
In your particular case, you do not need the val a
:
def example(something):something {
val c= yourListC ::: if(firstTest){
if(secondTest){
yourListA
}
else{
yourOtherListA
}
} else {
anAdequateEmptyList
}
}
Upvotes: 2
Reputation: 49705
Almost Everything in Scala returns a value (the exception is for statements such as package declarations and imports)
if/else statements, pattern matches, etc. etc.
This means that your if/else block returns a value, and is especially keen to do so, very much like the ?:
ternary operator in Java.
val foo = ... some integer ...
val bar = if(foo >= 0) "positive" else "negative"
Or using blocks:
val foo = ... some integer ...
val bar = if(foo >= 0) {
"positive"
} else {
"negative"
}
Nest 'em to your heart's content if you wish!
val foo2 = ... some other integer ...
val bar = if(foo >= 0) {
if(foo2 >= 0) {
"double positive"
} else {
"part-way there"
}
} else {
"foo was negative"
}
and even mix 'n' match styles:
println(
if(foo >= 0) {
if(foo2 >= 0) "double positive" else "part-way there"
} else {
"foo was negative"
}
)
Upvotes: 6
Reputation: 790
You can't make it visible outside declaration scope, so, maybe, try this:
def example(somthing):somthing{
val c = {
if (something) {
(0 to 10).toList
} else {
(0 to 5).toList
}
}
}
Upvotes: 6