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 _ => true
to 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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With