Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

From the article:

    val x = new Array[Integer](3)  //type inferred for x
    x(0) = 1
    x(1) = 2
    x(2) = 3
    
    for (y <- x if y > 2)
        println(y)
The idiomatic way to do this is:

    val x = Array(1, 2, 3)
That infers the type and sets values in one shot, with fewer characters. Also, using Integer (that's the java.lang.Integer) has been deprecated since 2.8.1 I believe. `Int` is preferred unless you really mean to use `Integer` (e.g. you're using a native Java library).


By not using the declaration, the type of x is Array[Nothing], and it lacks the `withFilter` attribute.


I'm not so sure about that...

    C:\Users\bert>scala
    Welcome to Scala version 2.9.2 (Java HotSpot(TM) Client VM, Java 1.7.0_06).
    Type in expressions to have them evaluated.
    Type :help for more information.

    scala> val x = Array(1, 2, 3)
    x: Array[Int] = Array(1, 2, 3)

    scala>
You can see that scala infers the type right (Array[Int]).


Even, I find this strange and I may be wrong. With your definition, when I use the for construct, I see this:

    scala> for (y<-x if x > 2)
         | println(y)
    <console>:9: error: value > is not a member of Array[Int]
              for (y<-x if x > 2)
                             ^

As you suggested, there may be a idiomatically better way to get implicit inference and also use the filters. I would be glad if some one corrects me on that.

Edit: Yeah, I see the silly error I made. I'll better get some sleep. I will leave this comment intact, for the responses to make sense.


You are comparing an array of integers with an integer. You would want to do this instead:

    for (y <- x if y > 2) ...


Get some sleep, then spend another week playing with Scala and its REPL. It's a terrific tool to learn. If you like Eclipse, install the Scala IDE and the Scala Worksheet. It's rough around the edges, but it's even better than the REPL.


Yes, I have been using the Scala IDE and Scala worksheet for my initial learning. As you said, it is great and more friendly than the REPL itself. It reminds me of Python Notebook in terms of being able to get good feedback and recursively edit.


Most folks find that the IntelliJ Scala plugin is the best tool rather than Eclipse.


Have you tried the Scala Worksheet for Eclipse? Pretty cool.

I see that the recently released IDEA 12 has a similar feature (but so far incomplete and undocumented according to their bug tracker).


You made a typo, it should be "y > 2" in your filter expression.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: