Why does Scala need parameterless in addition to zero-parameter methods?

前端 未结 5 1224
猫巷女王i
猫巷女王i 2020-12-04 17:58

I understand the difference between zero-parameter and parameterless methods, but what I don\'t really understand is the language design choice that made parameterless metho

5条回答
  •  死守一世寂寞
    2020-12-04 18:39

    Besides the convention fact mentioned (side-effect versus non-side-effect), it helps with several cases:

    Usefulness of having empty-paren

    // short apply syntax
    
    object A {
      def apply() = 33
    }
    
    object B {
      def apply   = 33
    }
    
    A()   // works
    B()   // does not work
    
    // using in place of a curried function
    
    object C {
      def m()() = ()
    }
    
    val f: () => () => Unit = C.m
    

    Usefulness of having no-paren

    // val <=> def, var <=> two related defs
    
    trait T { def a:   Int; def a_=(v: Int): Unit }
    trait U { def a(): Int; def a_=(v: Int): Unit }
    
    def tt(t: T): Unit = t.a += 1  // works
    def tu(u: U): Unit = u.a += 1  // does not work
    
    // avoiding clutter with apply the other way round
    
    object D {
      def a   = Vector(1, 2, 3)
      def b() = Vector(1, 2, 3)
    }
    
    D.a(0)  // works
    D.b(0)  // does not work
    
    // object can stand for no-paren method
    
    trait E
    trait F { def f:   E }
    trait G { def f(): E }
    
    object H extends F {
      object f extends E  // works
    }
    
    object I extends G {
      object f extends E  // does not work
    }
    

    Thus in terms of regularity of the language, it makes sense to have the distinction (especially for the last shown case).

提交回复
热议问题