Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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?

like image 445
oxbow_lakes Avatar asked May 25 '10 08:05

oxbow_lakes


People also ask

Does Scala support type inference?

The Scala compiler can infer the types of expressions automatically from contextual information. Therefore, we need not declare the types explicitly. This feature is commonly referred to as type inference. It helps reduce the verbosity of our code, making it more concise and readable.

What would be the type inferred by Scala compiler for variable?

Scala compiler can automatically infer types of each variable declared. If the value of a variable is declared in double-quotes it will automatically be inferred as String. Also, the compiler can infer any value in a single quote is inferred as Char. The compiler, by default it infer any number without decimal as Int.

How does Scala determine types when they are not specified?

For example, a type constructor does not directly specify a type of values. However, when a type constructor is applied to the correct type arguments, it yields a first-order type, which may be a value type. Non-value types are expressed indirectly in Scala.


1 Answers

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.

like image 67
Arjan Blokzijl Avatar answered Sep 30 '22 09:09

Arjan Blokzijl