使用花括号应用方法

时间:2013-06-18 03:37:04

标签: scala

为什么会这样:

  List(
   "string", "string2"
  )

但这不是吗?

  List{
   "string", "string2"
  }

编译错误:;' expected but ',' found.

但对于我自己的使用apply方法的对象:

object Dictionary {    
  ...    
  private[dictionary] def apply(words: List[Word]) = {
    ...
  }
}

Dictionary { // curly braces works fine
  List ( // but here, for List - I can Not use curly braces
    "hello", "hello2" 
  )
}

2 个答案:

答案 0 :(得分:3)

区别在于逗号 - 使用括号时,您只能使用逗号分隔的参数列表。

你会发现

List {
    3
}

工作正常。

答案 1 :(得分:1)

Canonical answer on bracesa supplement

The official glossary有助于调用块封装副作用和结果值。

最近在ML上发表了few opinions关于牙箍及其尖尖表兄弟的信息。

在某些情况下,将parens和braces视为某种可互换的方式也许是无益的。

使用exprs和块更容易思考,在这种情况下,函数args可以是逗号分隔的exprs或块。

相关问题