开发者

Scala type inference question

I was just pottering about with Tony Morris' excellent exercise on catamorphisms, when I was pondering what was happening in the following situation...

def cata[X](some: A => X, none: => X): X

Let me now call this method as follows:

def isDefined: Boolean = cata( _ => true, false)
开发者_Python百科

I was wondering whether the type inferencer determines the type of _ => trueto be A => Boolean or Any => Boolean. Due to the fact that Function1 is contra-variant in its input parameter, both of the following compile just fine:

def isDefined: Boolean = cata( (_: A) => true, false)    //#1
def isDefined: Boolean = cata( (_: Any) => true, false)  //#2

So the question is, does the type inferencer come up with #1 or #2?


I tried this out:


trait MyOption[+A] {
   def cata[X](some: A => X, none: => X): X
   def isDefined: Boolean = cata( _ => true, false)
}

and compiled this with scalac -Xprint:types. This gave the following output:


[[syntax trees at end of typer]]// Scala source: myoption.scala
package  {
  abstract trait MyOption[A >: Nothing : Nothing  X, none: => X): X;
    def isDefined: Boolean = MyOption.this.cata[Boolean](((x$1: A) => true), false)
  }
}

So by the looks of it, the type inferencer came up with option #1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜