In this Scala 2.13 example:
import scala.language.implicitConversions
object Main2 extends App {
trait Foo {
type F = this.type => String
}
def fooA[A <: Foo](f: A#F, toString: A#F => String): String = toString(f)
def fooB[A <: Foo](f: A#F, toString: (A => String) => String): String = toString(f)
}
It fails with:
type mismatch;
found : _1.type => String where val _1: A
required: A => String
def fooB[A <: Foo](f: A#F, toString: (A => String) => String): String = toString(f)
Why is A => String not the same as _1.type => String where val _1: A?
Is it safe to cast f.asInstanceOf[(A => String)]?
Is there a concrete example where this doesn't work?
I think you have misunderstanding what is
this.type. From scala 2.13 spec:It means, that
this.typewill be uniq for each instance ofFoo. InfooB:compiler sees that you tries to pass
fwhich type is:function from
singleton-type objecttoStringinto function what takes function from object of typeAintoString.Note object of type
A(new A()) has not the same type as(new A()).type, they have different types and this is the reason why compiler shows you an error.for example, you can write something like that and it will compiles:
because of
bar.typehas the same type asthis.type(they are both refer into one singleton type -bar.typeConclusion
Your functions
fooAandfooBhave different signatures,A#F => Stringis not the same asA => Stringand you can't useasInstanceOfon first.fooBwill not work on any instance ofFoobecause anyFooinstance has it's ownthis.typesingleton type. It doesn't relate toFoolike someFooimplementation relates toFoo.