Kotlin English to Norwegian (with Zip)

J Banks
Software Tidbits
Published in
2 min readJul 25, 2018
Merge Two Lists — zip

What is the Requirement?
An application has the need to translate a given list of English words to their corresponding Norwegian (bokmål) words.

val englishWords = listOf("I", "the", "is", "you", "not", "one", "and", "in", "have", "we")

How to Solve?
Using an existing language translation library API, the list will be translated from and to the languages supported. The library being used supports translation from English to Norwegian.

What does the API accept for input?
The translator library API accepts a list of words to be translated, the target ‘from’ language, and the translated ‘to’ language.

val norwegianWords = translate(
englishWords,
Language.ENGLISH,
Language.NORWEGIAN
)

What does the API return for output?
The translator library returns a single list of translated words in the order of each word provided in the input list.

for (x in norwegianWords) {
println(x)
}
jeg
det
er
du
ikke
en
og
i
har
vi

One problem.

The translator library doesn’t return the original set of words paired with the translated words. How can we easily cope with this on the receiving side to pair up the two lists?

One way, is to utilize Kotlin’s zip function. This function returns a list of pairs built from elements of both collections having the same indexes.

val wordDefs = englishWords.zip(norwegianWords)
for (pair in wordDefs) {
println(pair)
}
(I, jeg)
(the, det)
(is, er)
(you, du)
(not, ikke)
(one, en)
(and, og)
(in, i)
(have, har)
(we, vi)

And, if one would like a map form, that is fine, simple to do this with Kotlin, just use the toMap() function.

val mappedDefs = wordDefs.toMap()
for (pair in mappedDefs) {
println(pair)
}
I=jeg
the=det
is=er
you=du
not=ikke
one=en
and=og
in=i
have=har
we=vi

A powerful little function that can be used to join up (i.e. zip) two lists!

Until next time …

--

--