Skip to content

Strange type mismatch error when function type is expected + eta-expansion #24203

@unkarjedy

Description

@unkarjedy

Scala 3.7.3 with -explain compiler flag

Use the code example below:

class A

//
// Strange errors
//
def bar(): String = null
bar: (() => String) //OK
bar _: (() => String) //OK (with warning for deprecated `_`)

// Strange error: Found: () => Unit Required: A => Unit
val a: A => Unit = (bar _)
// Strange error: Found: String Required: Int
val b: A => Int = (bar _)

//
// Good errors
//
// Good error: Found: () => String Required: A => String
val c: A => String = (bar _)

val f: () => String = null
// Good error: Found: () => String Expected A => Unit 
val x: A => Unit = f
// Good error: Found: () => String Expected A => Int 
val y: A => Int = f
// Good error: Found: () => String Expected A => String 
val z: A => String = f

Note that for values c, x, y,z the type mismatch error text is quite expected.
However for a and b the errors look strange and misleading.

Foe example, for val a: A => Unit = (bar _) the error is as such:

Found: () => Unit
Required: A => Unit

Explanation
===========

Tree:

() =>
{
bar()
()
}

I tried to show that
() => Unit
conforms to
A => Unit
but none of the attempts shown below succeeded:

==> () => Unit <: A => Unit = false

The tests were made under the empty constraint

Why the explicitly-eta-expanded (bar _) was tried to be called and wrapped in () => { bar() } (leading to the strange () => Unit "Found" type)?

And for val b: A => Int = (bar _) it's

Found: String
Required: Int

Explanation
===========

Tree:

bar1()

I tried to show that
String
conforms to
Int
but none of the attempts shown below succeeded:

==> String <: Int = false

The tests were made under the empty constraint

Again, not clear, quite confusing.
Why the tree is not () => bar1() here?
Why it only checks the return type here ignoring the param types?

Similar situation with e.g.

def bar2(x: A): String = null
val a2: () => Unit = bar2 _
val b2: () => Int = bar2 _

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:reportingError reporting including formatting, implicit suggestions, etcarea:typerbetter-errorsIssues concerned with improving confusing/unhelpful diagnostic messagesitype:enhancement

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions