Difference between method and function in Scala

后端 未结 9 2041
温柔的废话
温柔的废话 2020-11-21 07:22

I read Scala Functions (part of Another tour of Scala). In that post he stated:

Methods and functions are not the same thing

9条回答
  •  一向
    一向 (楼主)
    2020-11-21 07:53

    One big practical difference between a method and a function is what return means. return only ever returns from a method. For example:

    scala> val f = () => { return "test" }
    :4: error: return outside method definition
           val f = () => { return "test" }
                           ^
    

    Returning from a function defined in a method does a non-local return:

    scala> def f: String = {                 
         |    val g = () => { return "test" }
         | g()                               
         | "not this"
         | }
    f: String
    
    scala> f
    res4: String = test
    

    Whereas returning from a local method only returns from that method.

    scala> def f2: String = {         
         | def g(): String = { return "test" }
         | g()
         | "is this"
         | }
    f2: String
    
    scala> f2
    res5: String = is this
    

提交回复
热议问题