如何访问scala匹配表达式之外的变量?

问题描述 投票:0回答:1

如何访问scala匹配表达式之外的变量“test”?即使我声明为 var,它也不会返回测试变量的更新值。

val x: Int = 2
var test=null
x match {
    case 1 => {var test=10}
    case 2 => {var test=11}
}
println(test)
scala
1个回答
0
投票

检查下面的代码。返回值并分配给测试变量。

val x: Int = 2
var test: Int = _
test = x match {
    case 1 =>  10
    case 2 =>  11
}
println(test)
test: Int = 11
© www.soinside.com 2019 - 2024. All rights reserved.