【问题标题】:Scala shorthand for declaring and returning a variable用于声明和返回变量的 Scala 简写
【发布时间】:2014-11-27 20:16:40
【问题描述】:

只是为了好奇有没有简写

test = "test"
test

我尝试过类似的方法

(test = "test")

//if ((test = "test") != null) test
if (test = "test") test

//编辑:我必须在返回之前设置测试变量。

【问题讨论】:

  • 你为什么要创建var?你能举出更大的例子来说明你想要完成的事情吗?
  • 此代码的简写为"test",前提是您避免使用显式返回语句。
  • 你通常不需要在 scala 中使用return,而且习惯上你应该避免使用它。只需将 "test" 作为函数的最后一条语句即可。
  • 我必须在返回之前设置变量

标签: scala shorthand


【解决方案1】:

你的例子没有多大意义。如果您在某个范围内,则无法从该范围外访问该范围内的 vars/vals/defs - 所以没有必要这样做。您只需返回值(使用隐式返回)。

"test"

【讨论】:

    【解决方案2】:

    根据https://stackoverflow.com/a/8845459/3641692这是不可能的

    我必须在多行上做:

    var test: String = null
    
    def setter(t:String): String = {
      test = t
      test
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      相关资源
      最近更新 更多