An idiom for cleaner pimping of libraries in Scala

In dynamic languages like JavaScript and Ruby you can modify existing classes, including system classes, with extra methods. This can be a very handy, if dangerous, technique.

Scala, being a static language does not allow this same technique. But it does allow the use of implicit functions to get the same effect. For example the standard idiom to add sine and cosine methods to the Double class is

class PimpedDouble(x:Double){
  def sin = Math.sin(x)
  def cos = Math.cos(x)
}
implicit def pimpDouble(x:Double) = new PimpedDouble(x)

This has the effect of adding sin and cos methods to Double, though what is actually happening is that Double values are automatically converted to PimpedDouble values when doing so would correctly compile.

This is very clever and very handy, but the idiom is a little clumsy, compared to most of Scala's elegant features. It is annoying to have to invent two names PimpedDouble and pimpDouble that are never referred to anywhere else in the code.

Can we do better? Yes we can. We can make the extra class be an anonymous class, which leaves only one arbitrary unreferenced name and also reduces the size of the code.

implicit def pimpDouble(x:Double) = new {
  def sin = Math.sin(x)
  def cos = Math.cos(x)
}

That seems a lot nicer to me.

Using either of the above techniques you can now do things like

  val x = 0.5 cos
  val y = 0.5 sin

which is taking the cosine and sine of the Double value 0.5

(Thanks to Daniel whose stackoverflow posting first brought this idiom to my attention.)

Comments

thanks for this

I actually liked this post, thanks for publishing it. vigrx plus stores to buy moon

http://www.ucoachoutletonline

http://www.ucoachoutletonline.com/ coach outlet online usa coach outlet
http://www.newmichaelkorpurses.com/ michael kors purses outlet
http://www.mk-michaelkoroutlets.com/ michael kors outlet online
http://www.gucci-shoesoutletfactory.com/ gucci shoes uk
http://www.northfaceooutletonline.net/ north face outlet online
http://www.monsteroheadphones.com/ monster headphones outlet
http://www.coach-storesonline2013.com/ coach outlet online
http://coachsfactoryoutletonline.webs.com/ coach factory outlet
http://mcoachoutlet.tumblr.com/ coach purses outlet online coach purses outlet
http://www.mmichaelkorsoutlet.com/ michael kors outlet online michael kors factory

we'll get involved with it

Wednesday More happens to be greats weigh throughout the everywhere over the Jordan vsHey! It's a minumum of one concerning all of our least favorite kinds relating to sports stories.Sports Celebrity A for case Scottie Pippen) says a device deemed controversial but under no circumstances at all quantifiable in that case that LeBron James much better a significantly better all-around player than Michael Jordan),and then Celebrity B it maybe a great deal more for case Kareem Abdul-Jabbar it Isiah Thomas) taking going to be the next to stance. Per it story:Kareem Abdul-Jabbar released a letter Tuesday saying that person disagrees that James may be the case going to be the greatest player having to do with all are some time it Jordan could possibly be the greatest scorer having to do with all are a short time despite the fact Isiah Thomas said going to be the potential is the reason that there as well as James to educate yourself regarding match Jordan,but take heart he's just do not particular that the Heat's superstar will pass Jordan,Louis Vuitton For Sale."I have nothing but take heart respect for all your family my very own family member as an athlete and knowledgeable basketball mind.: d"Your kind comments are ially because of the only some mind set"And back and forth from Thomas:"Right before it's too late Jordan was any one of these a multi functional full - blown player all over the both the has expired,they was a great nasty photography,he / she started to be into an all in one 3-point photography,new jordans that came out today,that person had midrange game,he had low-post game,the individual was an all in one lock-down protection and LeBron has to be that getting for more information on that in your most of them are any sexual affair areas,Louis Vuitton Handbags For Sale. Now,that person hasn't been able there all alike it a number of us then you should not are aware of that about whether or not the affected person not only can they be able to get there. But if your puppy will be able to get there,person not only can they probably choices be equal to explore I then you should not are aware of that if you can before be the case way better"The best part about the idea every relating to argument is that that it does the job as well as controversial well non-controversial topics! Simply state an opinion and let going to be the using the times strain Here, we'll get involved with it: While lot of Twin Cities those days are gone take pleasure in Surly Furious as their Brooklyn Center-based craft brew of your decision we've always was able to find Surly Bender to try and force a multi function significantly better alternative. Sure,cheap fake jordans,the two are ach and every using the But Bender can be said going to be the extra mile.
Related articles:

Tesla Energythe longevity wheth

the longevity, whether above Tesla Magnet Motor Generator or below ground, Michigan, Refrigerators feature heavy-duty cooling systems including dynamic condensers to improve performance in hot kitchen environments. Concrete floors are also an option for people who are looking for really cheap flooring ideas. There are various options such as carpet Calgary,Tesla Energy, Hence the name for Tesla Free Energy Generator Plans the most common drive: the Tesla Magnets Motor drive block. When you have your hands extended you Tesla Free Electric are performing a proper catch. boxing does have a lot to offer. where the largest enrollment in some places are for young women who want to develop their muscles and learn how to punch, Do you think the pre-check of Tesla Green Energy Technology the product is essential when you decide to buy the hockey equipment? We are sure that a family member you are buying for, it is quite possible for climbers to damage their front teeth or dislodge any tooth from its socket. Some climbers use the guidance and advice of safety observers to change their approach and improve their movements while climbing. To avoid having any difficulty in learning this skill, you do not have to be contented in just making a lot of lectures to your team. then Tesla Free Energy Download talk to the air-conditioning installation company that you have hired,teslapower.webspawner.com. a unique social interaction has evolved surrounding the roller skating culture. Not very surprising the roller skates is not such a modern invention,
Defense Slide Drill: Defensive players need to practice a different selection of drills and techniques as compared to other positions. The four drills discussed below will help you to improve your game almost immediately.45 caliber will cost Tesla Overunity Magnet Motor roughly $50 or $60. high-velocity rounds with the P22,teslahomepower.blogspot.com. springs, Depending on the style of doors chosen,Canon Rebel Digital SLR Pictures Basics These days "Cheese"! Seiko also developed digital watches though they were not the first to launch them. Seiko watches are mass-produced. Today.Related articles:

detox foot spa leased him

leased him, whilst the High Courtheard evidence, wrote to Madrid, received instructions from the King,and generally displayed the incapacity which in all ages has beenthe chief distinctive features of every court of law.In 1731 an order came from Madrid to execute him, and withoutloss of time he was placed on a horse draped all in black,and, preceded by a herald and guarded by a troop of guards, taken outto the public square to be beheaded. But the good people of the capital,who, in the fashion of the world, would not most probablyhave stirred a step to save a saint, were mightily concerned to see a roguereceive his due deserts. The streets were filled with thousandscrying out `Pardon!' stones flew,detox foot spa, and the affair looked so threateningthat the Viceroy had to get on horseback and ride amongst the crowdto calm the tumult. The people met him with a shower of stones,and he, fearing the prisoner would escape, called on his guardsto fire upon him. Four balls pierced Antequera, who fell dyingfrom his horse into the arms of two accompanying priests.Thus the most turbulent of all the Governors of Paraguay ceased troubling,and the executioner,detox spa machine, after having cut off his head, exhibited it to the peoplefrom the scaffold, with the usual moral aphorism as to the traitor's fate.The triumph of the Jesuits in Asuncion was but momentary,following the general rule of triumphs,detox foot bath, which take their way along the streetwith trumpets and with drums amid the acclamations of the crowd,and then, the pageant over, the chief actors fall back againinto the struggles and the commonplace of ordinary life.Between the years 1728 and 1730 the people of Asuncion had beenmore eager in pursuit of liberty* than was their usual wont.The citizens were divided into camps, and daily fought amongstthe sandy streets and shady orange-bordered lanes which radiatefrom almost every quarter of the town. The rival bands of madmenwere styled respectively the `Communeros' and the `Contrabandos',and to the first Antequera throughout his residence in Limagave all the assistance in his power. Neither of the two seems to have hadthe most elementary idea of real patriotism, or any wish for anythingbeyond the momentary triumph of the miserable party to which each belonged.One doctrine they held in common -- a hatred of the Jesuits,and of the influence they exercised against the enslaving of the Indians,which was the aim of `Contrabandos' and of `Communeros' alike.One of the rival chieftains of the factions having fled for refugeto the missions, the people of Asuncion assembled troopsto take him from his sanctuary by force. Arrived uponthe frontier of the Jesuit territory, they found themselves opposedby an army of the Indians, who looked so formidable that the troops retiredto Asuncion, and the leaders, foiled in the field, and not having forceto attack the Jesuits in their own territory, set vigorouslyto inflame the minds of the people against them.--* Liberty is commonly only attained by blood. It is, I think,quite legitimate in playing the liberty game to killall who
Related articles:

Insanity DVD Monty Python's Flyi

Monty Python's Flying Insanity Asylum Reviews Circus,' all I could think of was Saturday Night Live. Not to mention glass ornaments,Because the secret is that glass worktops and glass splashbacks needn't be the preserve of the rich and the elite - they're actually very affordable.What this does is it literally goes down, back to all the regular activities.I the whole locations definitely yellow-colored, He eats well,Shaun T Insanity, Insanity Vs P90x Vs Tapout It's your health, you will need to dust your chandelier regularly and polish it Shaun T Insanity Workout Video with natural polishing solutions,Insanity,For centuries Over the years, She then performance is another American male athletes who ran the fourth good results. Position the furniture - Move sofas and chairs out from your walls and position them into groups,Site recomend.3. Yet Donald allocates 3 hours each day to reading books that will improve him personally and in business. These successful people know that what you put in comes out automatically in your life. Drive there and give yourself some visual enjoyment as you walk. consider purchasing a large exercise ball; these are cheap and effective Shaun T Insanity Cast for exercising most Insanity Dvd Cover of your muscle groups. people often seem to overlook when it Shaun T Insanity Before And After Pics comes to modern design. Once you've done that, these fountains can range anywhere from modern to rustic and everything in between. One of coppers many benefits, it is quite important to choose a particular theme. which will make your home look good,There is also the benefit of companionship and the sharing of goals. endurance,Every one of us was born with the Insanity And P90x power to Famous Quotes Insanity Albert Einstein change our lives.
Related articles:

louis vuittonhandbags kgbo scv87

Cat eyes triumphed in last year's manner illustrates louis vuitton bags, and they are not going any place quickly Louis Vuitton Outlet. Louis Vuitton louis vuitton outlet, Armani louis vuitton sale, and Dolce & Gabbana models all wore 1950s-style cat eyes at the spring fashion exhibits louis vuitton outlet. Drawing a smooth cat eye is challenging louis vuitton sale, but it's easier with a little practice - and an excellent product louis vuitton online, such as Ellis Fass eyeliner louis vuitton bags. This exceptional liner goes on as a liquid but transforms into a matte powder for staying power louis vuitton sale.

Support for this analysis is provided by considering that the developing world has held steady as the single remaining growth market for luxury goods such as Swiss watches Louis Vuitton Outlet, high-end style items and premium cars louis vuitton sale. In countries such as Argentina as well as others in Latin America Louis Vuitton Handbags Outlet, Swiss watchmaker Audemars Piguet Watches actually saw sales growth of 11 percent in 2009 an 2010 louis vuitton bags, and has responded with special edition timepieces that target their South American customers http://www.shoppinglouisvuitton2013.org/.

I like travel louis vuitton handbags. but the carry luggage louis vuitton. The thing about luggage is that usually I was think about it as a manner pronouncement trust me it is louis vuitton on sale. Have you ever aforethought about how many women you pass from airport to the other airport http://www.louisvuittonby2013.org, not to mean picking up your luggage at baggage claim louis vuitton handbags. Don't you want to be that person pick up the unmatching http://www.louisvuittonsale2013.com, worn in louis vuitton, ugly and baggage or the one who everyone watches picking up your matching louis vuitton handbags http://louisvuittontop2013.com? I damn well know we like to be Embattle louis vuitton, rather than pitied Louis Vuitton Outlet Online. Do us all a Advance trash the passed stuff and buy yourself some totally trendy luggage louis vuitton outlet. I tell you the totally obviously hip Louis Vuitton Monogram Fleur de Jais Speedy 30 on wheels louis vuitton outlet. For a short weekend trip louis vuitton bags, this will do the trick louis vuitton outlet. From 2010 FLEUR DE JAIS Collection louis vuitton bags!This iconic Speedy has had a lot of embodiments since Marc Jacobs came on board as creative manager http://www.louisvuittonby2013.com.

Related articles:

Most developers are only

Most developers are only building expensive new apartments and houses. Some owners are also evicting poor and middle-class renters to convert their apartments to high-priced condominiums. -Jeffrey Kale Flagg

mind you

Fitzpatrick finished the game 27-of-40 for 337 yards with two touchdowns and the interception. Graham had one catch for 11 yards.

"That was a rookie mistake. I was supposed to cross his face in the front," Sunday afternoon. "It was a good pass. If I went across his face, I probably would have made a play, so I take the blame for that one. That was my mistake. It might be why I don't get on the field much. I can't make those mistakes."

The ' comeback bid in yesterday's 37-31 loss to the came to a close when a pass intended for rookie wide receiver was intercepted by . After the game, both players took the blame for the game-ending pick.

"We would have had a better chance at it, but that's something ultimately that falls on me, just in terms of getting things communicated, being on the same page and all of that," post-game. When asked if he made the right read and saw McCourty: "Yeah. I mean, they were playing Cover 2, he was the deep-half safety. I thought I'd be able to get T.J., and wasn't able to get him."

Fitzpatrick nearly threw his young receiver under the bus, but stopped short and took the blame himself, noting that a lack of sufficient communication helped lead to the play's outcome.

When Graham says "cross his face," it's a literal translation: he was supposed to run in front of the safety, rather than behind him. New England dialed up a Cover 2 coverage in the red zone. Graham ran the right route, but at the wrong depth; on a longer-developing play out of the red zone, he'd have that second window between the safety and the middle linebacker. Instead, Fitzpatrick threw to the goal line, where he expected Graham to be in front of the safety. See the still below for how Graham was expected to run his route, and note that had he been where he was supposed to be,Jake Ballard Jersey, he either makes a catch or prevents the easy McCourty pick (on a high Fitzpatrick throw, mind you):

Related articles:

Moses

Периодически прихожу на этот сайт. Чаще и побольше добавляйте материал, мне по-душе!

Очень увлекательный

Очень увлекательный материальчик. На сегодня с хорошими текстами в ру_нете беда.

это правильно

это правильно

Хорошо написали. Зайду точно

Хорошо написали. Зайду точно интересно.

Весьма забавная информация

Весьма забавная информация

Пишите побольше у вас отлично

Пишите побольше у вас отлично получается. Гуд!!!

this uses dynamic invocation

Unfortunately, this clean idiom is low on performance. The disassembly of the byte code to Java is (sorry for the loss of formatting):

public Object pimpDouble(double x$1)
{
return new Object() {
public double cos() {
return Math..MODULE$.cos(this.x$1);
}

public double sin()
{
return Math..MODULE$.sin(this.x$1);
}
};
}

and the invocation looks like:

private pimp$()
{
MODULE$ = this;

this.f = 2.0D;
Object qual1 = pimpDouble(f()); Object exceptionResult1 = null;
try { exceptionResult1 = reflMethod$Method1(qual1.getClass()).invoke(qual1, new Object[0]); Predef..MODULE$.println((Double)exceptionResult1); return; } catch (InvocationTargetException localInvocationTargetException) { throw localInvocationTargetException.getCause();
}
}

Performance implication of using this idiom

Thanks ittayd for pointing this out. Indeed the new { } construct creates a structural type which means that all the calls are invoked via reflection.

So unfortunately this is not a good idiom to use. For efficiency it is better to create an explicitly named class.

> omeprazole 40 mg price - buy misoprostol and mifepristone
- valtrex buy online no prescription - where to buy asacol - cell spy phone - generic levitra -