Notice the following strange behavior (Scala 2.9.1.RC2):
scala> val spam = x => log(x)
spam: Double => Double = <function1>
scala> val spam = x => log(x)*log(x)
<console>:10: error: missing parameter type
val spam = x => log(x)*log(x)
^
scala> log(2)*log(2)
res30: Double = 0.4804530139182014
How come Scala can infer the type of the first one but not the second?
Another strangeness:
scala> def eggs(foo:Int=-1) = foo
<console>:1: error: identifier expected but integer literal found.
def eggs(foo:Int=-1) = foo
^
scala> def eggs(foo:Int= -1) = foo
eggs: (foo: Int)Int
What's going on here? Why does it choke when there isn't a space between = and -?
Question 1. The surprise, to me, is that type inference succeeds at all. Another case that fails to compile is,
val spam = x => log(log(x))
Generally, the rule is that parameter types (here, x
) must be made explicit. But apparently this rule doesn't hold for the special case x => f(x)
, which gets rewritten to f _
. In other contexts, this rewriting leads to unspec'ed behavior.
Note: If there is an expected function type, then the parameter type need not be explicit,
val spam: Double => Double = x => log(log(x)) // OK
Question 2. Without the space, you've encountered the "operator" syntax for types. Here's an example that does compile,
trait =-[A, B]
trait One
def eggs(foo: Int=-One) = foo
This is equivalent to,
def eggs(foo: =-[Int, One]) = foo
The error message you got (identifier expected but...) is saying that the integer literal 1
is not a valid type.
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