Difference between method and function in Scala

后端 未结 9 2429
温柔的废话
温柔的废话 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:52

    In Scala 2.13, unlike functions, methods can take/return

    • type parameters (polymorphic methods)
    • implicit parameters
    • dependent types

    However, these restrictions are lifted in dotty (Scala 3) by Polymorphic function types #4672, for example, dotty version 0.23.0-RC1 enables the following syntax

    Type parameters

    def fmet[T](x: List[T]) = x.map(e => (e, e))
    val ffun = [T] => (x: List[T]) => x.map(e => (e, e))
    

    Implicit parameters (context parameters)

    def gmet[T](implicit num: Numeric[T]): T = num.zero
    val gfun: [T] => Numeric[T] ?=> T = [T] => (using num: Numeric[T]) => num.zero
    

    Dependent types

    class A { class B }
    def hmet(a: A): a.B = new a.B
    val hfun: (a: A) => a.B = hmet
    

    For more examples, see tests/run/polymorphic-functions.scala

提交回复
热议问题