Difference between method and function in Scala

后端 未结 9 2037
温柔的废话
温柔的废话 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 08:14

    Let Say you have a List

    scala> val x =List.range(10,20)
    x: List[Int] = List(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
    

    Define a Method

    scala> def m1(i:Int)=i+2
    m1: (i: Int)Int
    

    Define a Function

    scala> (i:Int)=>i+2
    res0: Int => Int = 
    
    scala> x.map((x)=>x+2)
    res2: List[Int] = List(12, 13, 14, 15, 16, 17, 18, 19, 20, 21)
    

    Method Accepting Argument

    scala> m1(2)
    res3: Int = 4
    

    Defining Function with val

    scala> val p =(i:Int)=>i+2
    p: Int => Int = 
    

    Argument to function is Optional

     scala> p(2)
        res4: Int = 4
    
    scala> p
    res5: Int => Int = 
    

    Argument to Method is Mandatory

    scala> m1
    :9: error: missing arguments for method m1;
    follow this method with `_' if you want to treat it as a partially applied function
    

    Check the following Tutorial that explains passing other differences with examples like other example of diff with Method Vs Function, Using function as Variables, creating function that returned function

提交回复
热议问题