Scala - 如何使val可见

时间:2011-01-25 12:14:40

标签: scala visibility

我有这个方法

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
}

如何声明并使其可见? 我不能使用var

3 个答案:

答案 0 :(得分:6)

你无法在声明范围之外看到它,所以,尝试这个:

def example(somthing):somthing{    
  val c = { 

    if (something) {
      (0 to 10).toList
    } else {
      (0 to 5).toList
    }

  }
}

答案 1 :(得分:6)

Scala中的 Everything 几乎返回一个值(例外是包声明和导入等语句)

if / else语句,模式匹配等等。

这意味着你的if / else块返回一个值,并且特别热衷于这样做,非常类似于Java中的?:三元运算符。

val foo = ... some integer ...
val bar = if(foo >= 0) "positive" else "negative"

或使用块:

val foo = ... some integer ...
val bar = if(foo >= 0) {
  "positive"
} else {
  "negative"
}

如果你愿意,可以把它们放在心里!

val foo2 = ... some other integer ...
val bar = if(foo >= 0) {
  if(foo2 >= 0) {
    "double positive"
  } else {
    "part-way there"
  }
} else {
  "foo was negative"
}

甚至混合'n'匹配样式:

println(
  if(foo >= 0) {
    if(foo2 >= 0) "double positive" else "part-way there"
  } else {
    "foo was negative"
  }
)

答案 2 :(得分:2)

在您的特定情况下,您不需要val a

def example(something):something {
  val c= yourListC ::: if(firstTest){
                         if(secondTest){
                           yourListA
                         }
                         else{
                           yourOtherListA
                         }
                       } else {
                           anAdequateEmptyList
                       }
}