Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bugs or weird behaviors in Scala 2.9

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 -?

like image 977
Urban Vagabond Avatar asked Dec 22 '22 08:12

Urban Vagabond


1 Answers

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.

like image 92
Kipton Barros Avatar answered Jan 02 '23 17:01

Kipton Barros