Understanding the type of inferrence in Scala

I wrote the following simple program:

import java.util.{Set => JavaSet} import java.util.Collections._ object Main extends App { def test(set: JavaSet[String]) = () test(emptySet()) //fine test(emptySet) //error } 

Demo

And I was really surprised that the final line of test(emptySet) not compiled. What for? What is the difference between test(emptySet()) ? I thought that in Scala we could freely exclude parentheses in such cases.

+7
methods scala
source share
1 answer

See Converting Methods in the Scala Specification:

The following four implicit conversions can be applied to methods that do not apply to the argument list.

Rating

The parameterless method m of type => T is always converted to type T, evaluating the expression to which m is bound.

Implicit application

If a method accepts only implicit parameters, implicit arguments are passed by the rules here.

Eta p extension>

Otherwise, if the method is not a constructor, and the expected type pt is a functional type (Ts ') ⇒ T', eta-decomposition is performed by the expression e.

Empty application

Otherwise, if e is of method type () T, it is implicitly applied to the list of empty arguments, which gives e ().

The one you want is the "Empty Application", but it only applies if none of the previous conversions are performed, in which case "Eta Expansion" occurs instead.

EDIT: That was wrong, and Jasper-M's comment is right. No this-extension occurs, the "Empty Application" is simply not applicable to common methods at this time.

+4
source share

All Articles