Why can't I omit "apply" in this.apply (_) in Scala?

Observe the following code

trait Example { type O def apply(o: O) def f(o: O) = this.apply(o) } 

which compiles to Scala. I would expect that I can leave apply as usual by writing def f(o: O) = this(o) . However, this results in an error message.

 type mismatch; found : o.type (with underlying type Example.this.O) required: _31.O where val _31: Example possible cause: missing arguments for method or constructor 

Can someone explain to me what is going on?

+6
source share
2 answers

The accepted answer is incorrect. You can conclude that the actual problem is that this compiles fine:

 trait Example { def apply(o: String): String = o def f(o: String) = this(o) } 

this (...) only represents a constructor call when the call site is an auxiliary constructor. For the remainder of the time, this is a call for use, as you imagined.

+4
source

You cannot, because this () inside the constructor is a call to this constructor of objects ( this () somewhere else generates a compilation failure) and cannot be made to the apply () call, because it will hide the constructor and make it impossible to call another constructor in your object. this (args) is always a call to the constructor method (in both Java and Scala), so when inside your own object you must always explicitly call apply (args) .

+11
source

Source: https://habr.com/ru/post/904440/


All Articles