Introduction
If you find yourself looking for a nice way to work with Google Translate service or Microsoft Translator service in Scala, then this short article will give you a quick tip of how to do it in a fancy non-blocking way. I would suggest you use a fluent-translator library which has a nice convenient DSL and promises not to do any blocks along the way.
Using the Code
Scala allows you to build DSLs that look almost like normal English sentences. That's why the following examples of using Microsoft Translator are so easy to understand:
import com.smartelk.fluent.translator.Dsl._
implicit object client extends MicrosoftTranslatorClient {
val clientId = "microsoft client id"
val clientSecret = "microsoft client secret"
}
Microsoft give me a translation of "Comment vas-tu?" to "en" as future
Microsoft give me a translation of "What a lovely weather today!"
from "en" to "fr" withContentType `text/html` as future
Microsoft give me many translations of "Doing well by doing good"
from "en" to "ru" as future
Microsoft give me translations(3) of "Paris holidays" from "en" to "ru"
withCategory "general" as future
Microsoft speak "I'm doing well enough now" in "en" withAudioContentType `audio/mp3`
as future
Microsoft speak "How are you doing?" in "en" withQuality MinSize as future
Using Google Translate would be just as easy:
import com.smartelk.fluent.translator.Dsl._
implicit object client extends GoogleTranslatorClient {
val apiKey = "google api key"
}
Google give me a translation of "Comment vas-tu?" to "en" as future
Google give me a translation of "What a lovely weather today!"
from "en" to "fr" withContentType `text/html` as future
As you see, all invocations return Future. Future in Scala represents operation being performed in parallel which result may not yet exist. Of course, just having Future in application doesn't mean that everything is "non-blocking": going parallel doesn't prevent you automatically from doing blocks in separate threads. That's why fluent-translator
does its best to guarantee a real non-blocking workflow. For this to be done, Akka and Dispatch libraries are used underneath to help with asynchronous processing.
Points of Interest
I hope someone will find this quick introduction to fluent-translator
useful. The library is on GitHub and all those who are interested are welcome to contribute.