Scala - 如何使val可见

D4N*_*iel 1 visibility scala

我有这个方法

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
}
Run Code Online (Sandbox Code Playgroud)

如何申报并使其可见?我不能用var.

小智 6

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

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

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

  }
}
Run Code Online (Sandbox Code Playgroud)


Kev*_*ght 6

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

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

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

val foo = ... some integer ...
val bar = if(foo >= 0) "positive" else "negative"
Run Code Online (Sandbox Code Playgroud)

或使用块:

val foo = ... some integer ...
val bar = if(foo >= 0) {
  "positive"
} else {
  "negative"
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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