scala学习笔记1: scala method

刚接触scala,做练习的时候碰到一个问题,顺便mark一下。

先看下面一段代码:

 1 def sum(args:Int*) = {
 2   var result = 0
 3   for (arg <- args)
 4     result += arg
 5   result
 6 }
 7 
 8 object ScalaApp {
 9   def main(args: Array[String]): Unit = {
10     val s = sum(1, 4, 9, 16, 25)
11     println(s)
12   }
13 }

上面的代码运行以后报错如下:

Error:(1, 1) expected class or object definition
def sum(args:Int*) = {
^

可下面的代码却能顺利跑出结果

 1 object ScalaApp {
 2 
 3   def sum(args:Int*) = {
 4     var result = 0
 5     for (arg <- args)
 6       result += arg
 7     result
 8   }
 9 
10   def main(args: Array[String]): Unit = {
11     val s = sum(1, 4, 9, 16, 25)
12     println(s)
13   }
至于原因是什么,其实可以用一句话解释:方法是面向对象设计中类中的一部分,它必须依赖于类而存在。
原文地址:https://www.cnblogs.com/superhedantou/p/5645437.html