• Home
  • RSS Feed
  • Log in

Starting out with Scala
Posted by Arjan Blokzijl around lunchtime: July 3rd, 2009

Scala has become more and more popular over the recent months/years. Its hybrid nature of being an imperative as well as functional language attracts a crowd from the Java world as well as functional fundamentalists coming from the world where statements like x=x+1 are looked at with the utter disbelief. It has been stated that Scala is 'Java as it should have been', but there are also numerous complaints about the language and its features (like not being side effect free, overly complex, too much of everything, too much abstraction, having a weird syntax, etc). The latter might actually be a proof of its popularity, since people seem to be actually using the language instead of just looking at it briefly and stopping, tired but happy, after having written hello world with it.
In this blog post, I'll give you some (hopefully) useful tips how to best start if you want to learn this language, which is one of the candidates become 'our next big language' and surpass Java in this respect.

Pick an IDE, or not
The first problem you might encounter is that the various Scala IDE plugins have not yet reached the maturity of the Java support that you might have been accustomed to. Lots of hard work is in progress on this, but you still might experience hickups and freezes (as I have) of your favorite IDE. At this moment, the Netbeans plugin seems to be the most stable (this is the IDE that David Pollak, creator of Lift, seems to use). If you're an eclipse user, you'll probably want the nightly build version of the Scala plugin, since that's the only one actively under development. This means that you need the Scala trunk to work with, however.

There's also plenty of support for non-IDE's, and recently I've tried switching back to emacs again. For some, this brings back memories to good old university days, others may find it the utmost horror. I must say, I found it to be a rather soothing experience after years of development using Eclipse. You'll need to do some setup work to get a good Scala experience. An excellent blog post describing how to setup your emacs environment for Scala using Yasnippet, exuberant ctags and maven can be found here.

Try out the trunk
The latest released version of Scala is 2.7.5. The next version will be 2.8.0, but its release date is still not known. However, the invaluable Paul Philips has done many bug fixes and improvements in the Scala compiler and the REPL, all hanging out in the trunk. To take full advantage of this, check out the sources and build them. Note that the Scala collections API has been redesigned in the trunk, and differs from the 2.7.5 release. To get a good understanding of the new design, and the API in general, you're encouraged to read the new collection SIP (Scala improvement proposal) available here.

Read a book
The standard work is Programming in Scala, co-authored by Martin Odersky (creator of Scala) himself. This book is lengthy but very thorough, providing plenty of examples. Another book that has seen the light is Beginning Scala by David Pollak (already mentioned). I have not read this, but reviews suggest this is also an excellent start. More books will hit the market this year.

Check out Lift
Eventually it is possible that you might start to really like Scala and want to use it in the enterprise. Lift is the first web framework written in Scala, created by David Pollak. Downloading and creating a simple web application to work is a no-brainer. The distribution comes with plenty of maven archetypes to get a basic web application ready in under than five minutes. Lift has its own database mapping framework, but there's JPA support as well, if you like this. JTA integration is also being worked on.

Read some articles
There are loads of (both academic and slightly less academic) articles about Scala. For example, if you want to know the rationale behind Scala's actor library design, read the scala actor papers.
Martin Odersky's homepage also contains a long list of his publications.
It provides lots of material to provide insight in the design of Scala and its libraries. If you're not that academically inclined and from a Java background, try The busy java developer's guide to Scala, by Ted Neward. Provides a nice introduction.

Read some blogs.
Plenty of blogs available, here are some I like:

  • Daniel Spiewak Lots of useful Scala examples.
  • Tony morris. He's the creator of functional java and of Scalaz. Beware however, if you check this out you might end up in deep functional waters where Monads reign.
  • Jonas BonerHe has lots of experience of using Scala in the real world, some of which he has blogged extensively about. Well worth the read.
  • Planet Scala Perhaps you don't even need more than this. This aggregates numerous blog posts (including the one mentioned above) about Scala.

Join IRC
Scala has an IRC channel, which can be found here. Whenever you're stuck at some problem you're working at, there's always the mailing lists, but many knowledgeable people hang out on a daily basis on the IRC channel. Use lodgeit to show the code you're stuck with, and you'll get an answer in no time.

Start coding.
Lift might be the choice if you really want to write some useful, practical real world web applications. If you're totally impractical like me, pick a few problems from project euler, or the 99 problems projects (solutions in Scala can be found here. Many excellent programmers have taken this path, it's fun and an excellent way to play around with the core Scala API.

To put into practice what I preach here, a few lines of Scala code to either whet your appetite or make you run away screaming. Note that my Scala knowledge is still in the pre-kindergarten stage, I'm barely able to speak, so laugh at will when viewing this code.

First, a randomly picked Euler problem, number 48, just because I like onliners:

(1 to 1000).map(x => new java.math.BigDecimal(x).pow(x)).reduceLeft((a,b) => a.add(b)).remainder(new java.math.BigDecimal(10).pow(10))

This one liner is not nearly as concise and neat as the Haskell version, but it will do. If nothing else, it has at least has the tiny merit of showing Scala - Java interoperability.

Another randomly picked and slightly more complex one, problem number 21:

object Euler21 {
  def sumOfDivisors(number: Int): Int = {
    List.range(1, number).filter{i => (number % i) == 0}.foldLeft(0){(a,b) => a+b}
  }

  def solver(): Int  = {
      (for (i <- 0 until 10000; di = sumOfDivisors(i); if(di > i && sumOfDivisors(di)  == i) ) yield (i+di)).foldLeft(0){(a,b) => a+b};
  }
}

Enjoy.

  • Share/Bookmark

Tags: Scala
Filed under Scala | 9 Comments »



9 Responses to “Starting out with Scala”



    Boudewijn van Klingeren Says:
    Posted at: July 3, 2009 at 2:17 pm

    Hi Arjan,

    I would like to notice that IntelliJ IDEA also has a very good plugin for Scala development. I’m not sure how stable it is, because I haven’t played with it that much yet, but it defenitely is worth mentioning.

    Cheers,

    Boudewijn



    Arjan Blokzijl Says:
    Posted at: July 3, 2009 at 2:43 pm

    Apparently, the stability still leaves something to be desired: http://twitter.com/jboner/status/2402541265 :-) .
    I’ve used it very briefly at the end of last year, and I must say that it had the most impressive Scala plugin of all three (Netbeans, Eclipse, Intellij) at that time in my opinion.



    Twitted by bubbl_scala Says:
    Posted at: July 6, 2009 at 1:56 am

    [...] This post was Twitted by bubbl_scala [...]



    Sean Bowman Says:
    Posted at: July 6, 2009 at 5:14 am

    I liked the idea of Scala, but when it came right down to it, the execution just left a bad taste in my mouth. I came to it from Ruby (though I had years and years of Java before Ruby). Definitely much better than Java, but I kept trying to chain collection-related commands together, and they kept spitting back different, incompatible things. Then I spent all my time trying to figure out how to convert between the various collection return types into something useful.

    I know I’m not explaining the problem very well, and maybe it’s no longer a problem. I left Scala behind after writing a few things in it about a year or so ago. Maybe if they’ve figured out the collections, I should give it another shot…suggestions on where to look for help with those collections commands would be appreciated. Maybe I just didn’t “get it” my first go-around.



    Kieron Wilkinson Says:
    Posted at: July 6, 2009 at 1:55 pm

    Sean: That exact collection problem has been is fixed in version 2.8, which should be going final in a few months time. Even though it is not yet final, it is easily stable enough to play around with.



    Scala Lifting Off ? - Technology Says:
    Posted at: July 10, 2009 at 8:01 pm

    [...] NetBeans seems to be ahead of the curve in its support for [...]



    Paul Phillips Says:
    Posted at: July 23, 2009 at 5:30 pm

    In trunk I can express problem 48 like so:

    def bd(x: Int) = BigDecimal(x) pow x ; (1 to 1000 map bd sum) remainder bd(10)

    res0: BigDecimal = 9110846700

    (Hoping that’s correct, have no idea…)



    Arjan Blokzijl Says:
    Posted at: July 26, 2009 at 6:20 am

    Correct or not, it’s certainly neat and concise, much better than my version, thanks!



    Scala: всё только начинается? - Technology Says:
    Posted at: August 3, 2009 at 1:00 pm

    [...] NetBeans похоже не собирается отставать от прогрессивного мира, и тоже добавляет поддержку [...]



Leave a Reply

Click here to cancel reply.

Deployment automation for Java application running on Websphere, WebLogic and JBoss

Archives

  • January 2010
  • December 2009
  • November 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009

Xebia Sites

  • Xebia Corporate
  • Xebia France
  • Xebia India

Categories

  • Java (279)
  • Agile (109)
  • General (50)
  • Testing (42)
  • Performance (42)
  • Hibernate (36)
  • Scrum (33)
  • Podcast (31)
  • Architecture (31)
  • Spring (28)
  • SOA (24)
  • Maven (22)
  • Project Management (22)
  • Flex (17)
  • JPA (17)
    • JPA implementation patterns (13)
  • Eclipse (15)
  • Quality Assurance (14)
  • Middleware (19)
  • Frameworks (13)

Tag Cloud

    JavaOne Groovy Ajax Hibernate Maven Java Scala XML Architecture IntelliJ Agile Grails SOA Introduction to Agile Semantic Web Xebia esb Seam Closures Lean Scrum qcon Agile Awareness Workshop Poppendieck Spring Testing Functional Programming fitnesse Performance product owner
medicin depression buy phentermine without a perscription aricept generic hair loss help how do you prevent bone loss urinary tract infection symptoms viagra sex domination cialis viagra cures for throat infection buy sumycin acne care new medication for cancer treatment help for sleeping problems on-line pharmacies cure snoring medications to help clot blood what is aspirin buy zestoretic bronchitis vs pneumonia back pain muscle acne face medication muscle women pain behind knee fat blocker man health arthritis natural cure woman health women insomnia cheap phentermine online cats and irritable bowel syndrome buy cialis generic online nutritional diet for osteoporosis abnormal blood clots treatments for hair loss what is zyprexa dental whitening products impotence herbs drugs for diabetes allergy prevention buy canada levitra Mentax adhd in children hair loss in woman medicines for blood clot online imitrex viagra buy free dog products clindamycin drug how to stop hair loss chloramphenicol discount drug viagra what valium does permanent hair loss heart failure medicine avapro 150mg ordering viagra online food allergies order viagra online online viagra prescription carisoprodol mg improve your skin discount erectile dysfunction medication buy xanax online buy order viagra scabies teatments information allegra vitamine b1 diazepam breast cancer support free stop smoking cipro side effects ultram cheapest treatment attention deficit disorder discount vitamins supplements how to get viagra online synthroid buy cheapest cialis zyrtec online how to clear acne preventive osteoporosis immune stimulants what is hoodia On Line Viagra getting over the pain diflucan dosage health asthma online stores hair loss products blood clot drugs colon parasites hair loss products discount medicine pravastatin buy griseofulvin tablets order indomethacin dog health products how to take a beta-blocker diazapan is valium treating cold sores chronic pain drug what is osteoporosis stress drug tooth whitening lowering cholesterol naturally legality of buying cialis online order levitra treatment for insomnia cheapest cialis index depakote overdose alprazolam condom sales treatment of yeast infection xanax sales taking viagra after cialis how to control pain new birth control chest pain health prozac prescription blood clots viagra in mexico chlamydia pill cancer drugs cold flu drugs how do i order viagra online super viagra acyclovir medicine benadryl dosage erythromycin pregnancy buy contoured condom chronic muscle pain pet health dogs treatment attention deficit disorder dental teeth whitening asthma medicine free prescription drugs herpes drug diabetes treatment buy tooth whitening gel cheap fast valium generic levitra buy cheapest viagra online lopressor drug pharmacy drug prices ultram dosing treatments for bipolar disorder neurontin withdrawal parasite medication chlamydia tips for increasing breast size ways to enhance breast what is valium used for metformin tablet order birth control hair loss for men how does xanax work treatment hepatitis c rythmol cheap acai antioxidants nexium generic blood pressure pills levitra online no prescription Levitra Online medications on line motion sickness drugs bactrim online order roxithromycin nicotine where can i order viagra immune supplements buy erexin v bph prostate allopurinol xanax for depression drug new smoking stop cheap impotence drug generic cialis delivery new treatment for depression antibiotics for cat viagra china alternative medicine cholesterol viagra dose anxiety disorder treatment severe muscle pain treatment of cancer calcium carbonate penis enlargement without pill valium maximum dosage reasons for high blood pressure energy product breast enlargement info cheap effexor building your body wrinkle cream aricept dosage alpha blocker increasing female sex drive valium depression new pain meds no rx xanax drug trileptal mg imitrex avapro 150mg medicine drugs contraception female claritin pill medication for acne med orders buy viagra internet levitra effect treatment for blood clots order sominex buy creatine buy precose cheap viagra overnight lopressor drug body building info health drugs general health and medical what is diazepam eye infections in dogs online prescription pills diclofenac tablet new medication anxiety buy citalopram medication male enhancement enhancement fat blocker medicine for throat infection order cardizem about soma health remedies for dogs generic xanax cheap zyrtec for depression medicine viagra sex domination buy acne skin care product hypnosis help study cure vaginal yeast infection weight loss supplement program muscle pain in leg how to increase erection buy viagra what is cla augmentin doses gaining muscle mass health med online heart rate treatments lopressor drug dog ear canal phentermine without prescription viagra order online weight loss glipizide diabetes astelin generic fat blocker buy gel tooth whitening cheap wellbutrin online weight loss program buy antiox anti-biotics acne skin treatmen tramadole vpxl pill drugs affecting levitra immune system support augmentin hypothyroidism medication buy erexin v uy prescription medication without a prescription buy discount order osteo arthritis online buy pilocarpine cheapest place to buy phentermine parasite treatment impotence help body fat loss viagra herb alternative constipation supplements treatment dementia adhd and medications muscle spasm relief viagra online cheap relieve upper back pain stop hair loss discount viagra online menstrual cycle problems antifungal shampoo side effects ativan gabapentin medication where can i buy viagra diazepam buy soma online clonidine dosage viagra gel top hair loss fast antibiotics cure chlamydia skin fungal infections drug zofran give up smoking alternative medicine cholesterol sleeping help best online viagra scams prednisone 10mg viagra sex domination lotensin easy weight loss pain meds without prescription over the counter drugs new high blood pressure medic generic compazine cetirizine drug order phentermine best fat blockers woman enhancement supplement drug zofran buy precose new drug treatment for cancer how to increase fertility viagra in australia benadryl dosing buy alcoholism medications order l arginine buy diazepam generic for ativan ativan prescription drugs weight loss treatment for chest pain woman health where can i buy phentermine online skin fungal infection give up smoking viagra on line hoodia information how does osteoporosis occur buy viagra online buy alcoholism medications depakote overdose klonopin pill tetracycline capsules what is high blood pressure bladder control for dogs generic for lipitor glucophage online pharmacy gabapentin dosage treating yeast infections dog health info cymbalta anxiety cheap tramadol without prescription hydrea drugs used for cancer cure for high blood pressure alcohol and valium relief from constipation liver infection treatment cialis soft zantac medication help sleep problems all natural antibiotics order medication without prescription sleep problems free hypnotherapy gaining muscle mass cheap viagra order online natural help for pain how to buy viagra drug price celebrex information otc diuretic levitra 10 mg buy medicine online pets products relief foot pain cialis without prescription med care cheapest generic cialis rapid hair loss pain medications generic side effects meds without prescriptions cat anxiety buy simplicef natural cure arthritis effects of high blood pressure lowest price generic viagra how to get birth control new breast cancer drug buy topamax blood pressure meds when are beta blockers prescribed how to get pain meds order fosamax online viagra name order viagra viagra cialis cat's eye health how to relieve lower back pain treating ear infections diazapan is valium online pain doctors high blood pressure in elderly medication to stop smoking wellbutrin dosages diabetes blood sugar levels weight loss diet pill side effects of prescribed pain pills drug list high blood pressure buy cialis online in usa ultram cost how to help osteoporosis how to use clomid discount brand viagra wellbutrin cymbalta buy pills without a prescription buy pain medicine online tab tramadol depression symptoms treatment how levitra work hypertension medications beta blockers prevent premature ejaculation xanax interactions with other medicines purchase medicine on line does alli work xenical mexico prescriptions buy sumycin uy prescription medication without a prescription ambien cost methocarbamol effects cheap beta blockers cats bladder reduce cholesterol naturally metformin tablet scabies medicine breast enhancer pills body building over 50 order viagra cheap zestril medication how to buy prescription medications online pharma kamagra drugs depression ear infection symptoms big muscle controlling blood pressure pain meds and pregnancy buy diazepam without prescription skin allergies antibiotic zoloft buy weight loss nutrition program Buy Cialis breast increase meds without prescriptions blood clots medical edema treatment for flu best hangover remedy diabetes drugs