Startec

Startec

From Java to Kotlin, first impression on for loops

Mai 26, às 05:49

·

3 min de leitura

·

0 leituras

What? This was supposed to be like Java? I can't even write a for loop?! Or, at least, that was my first impression of Kotlin. I tried to write for (int i = 0...) but then I quickly adapted to for (var i =...
From Java to Kotlin, first impression on for loops

What? This was supposed to be like Java? I can't even write a for loop?!

Or, at least, that was my first impression of Kotlin.
I tried to write for (int i = 0...) but then I quickly adapted to for (var i = 0...) and then for (var i = 0 : Int....) but realised that I was going nowhere.

After scratching my noggin and saying a few curses self-encouraging words. I opted in for the regular enhanced for loop instead. But alas for (n : ints) also resulted in a compilation error.

So lets dive in to what I should have done.

Quick disclaimer is that the IntRange object, as well as the other ranges in the kotlin.ranges package are easy, and often used in, for instance, loops. They can be easily created like the following examples:

val intRange = (1 .. 5)
val theEntireEnglishAlphabet = ('a' .. 'z')
// The ".." operator makes it an ascending range. 
// Another option, is to use the until or downTo keywords
val theSameAsIntRange = (1 until 5)
val descendingIntRange = (5 downTo 1)

Enter fullscreen mode Exit fullscreen mode

So, back to what this article is all about, how do I use for loops?

Here are some examples!

// the regular, wonderful, enhanced for-loop
val someArr = intArrayOf(5, 3, 6, 32, 20, 1)
fun enhancedLoop() {
 for (num in someArr) {
 println(num) // -> console: 5, 3, 6, 32, 20, 1
 } 
}

Enter fullscreen mode Exit fullscreen mode

Yes! A loop! 🙌 But how do I get the indexes? 🤔
There are 2 ways of easily achieving this. One using the .indicies property(?) that you'll find on all of the Arrays and Collections that returns a... you guessed it! IntRange.


// using the .indicies 
val someArr = intArrayOf(5, 3, 6, 32, 20, 1)
fun loopWithIndex() {
 for (i in someArr.indicies) {
 println(i) // -> 0, 1, 2, 3, 4, 5
 }
}
// and if you're looking to loop until a certain value.
// you can just create a new range
// top level: private const val MAX_LOOPS = 5 
fun loopWithInlineRange() {
 for (i in 0 .. MAX_LOOPS) { // you can also use the "until" keyword for increased readability 
 println(i) // -> 0, 1, 2, 3, 4, 5
 }
}
// and if you'd like to do it descending, most likely just 
// a "backwards loop" 
val someOtherArr = intArrayOf(1, 2, 10, 4, 5)
fun loopDescendingWithRange(){
 for (i in someOtherArr.size -1 downTo 0){
 println(someOtherArr[i]) // -> 5, 4, 10 2, 1
 }
}

Enter fullscreen mode Exit fullscreen mode

I hope you found this little read helpful. I missed my good 'ol for (int i = 0; i < whatHaveYou.length(); i++) in the beginning, but rather quickly grew fond of the usage of ranges instead.


Continue lendo

TabNews

Como criar um git/github (e as primeras configs) obs: no windows e com o vscode · NicolasdevNx
Olá, este "artigo" tem como objetivo ensinar como baixar e usar o git eo o github(para este não é neseçario o dowload) então vomos lá. 1:Acesse o site https://git-scm.com/downloads escolh...

Hoje, às 02:32

TabNews

DUVIDAS SOBRE VUEJS E ARRAY PODE ME AJUDAR? · heuderdev
Boa noite a Todos! Pessoal, como eu posso percorrer esse array verificando se o numero que vem na function setActiveNumber(6), é igua a do array se for marcar o active como true, import {...

Hoje, às 00:27

DEV

CSS code refactoring
To refactor means to restructure the source code of an application or piece of software in order to improve operation without affecting functionality. Programmers should abide by the D.R.Y. (Don’t Repeat...

Mai 27, às 23:23

TabNews

Por que só sendo um bom programador não é possível ganhar dinheiro? · OzzyGomes
Ok, antes de tudo, eu sei que o título talvez pareça sensacionalista. Você deve estar pensando, eu sou programador, tenho um emprego que me dá dinheiro em troca dos meus códigos. E sim é...

Mai 27, às 23:16

Hacker News

Google account deleted after 2 hours of Aurora
Recommended alternatives for all the Google products, software and services NOTE: We're trying to recommend you alternatives which are FOSS (or mostly so) and privacy-respecting. This is by no means an...

Mai 27, às 22:20

Discovery

Google Maps completa 18 anos: saiba como tudo começou
O Google Maps, um dos serviços mais icônicos do Google, celebra seu 18º aniversário. Desde o seu lançamento em maio de 2005, ele tem sido uma ferramenta essencial para pessoas ao redor do mundo. Mas como tudo...

Mai 27, às 22:03

Discovery

Como criar um site gratuito no Google Sites
O Google Sites é uma ferramenta gratuita que permite criar um site sem a necessidade de conhecimentos em programação ou design. Com ela, é possível criar um site simples em questão de minutos e compartilhar...

Mai 27, às 21:53

Discovery

Google alerta para dispositivos 'Android TV' vendidos online que não são seguros
O Google está alertando os usuários sobre problemas de segurança relacionados a dispositivos “Android TV” vendidos online que não são seguros. Muitas desses hardwares usam o Projeto de Código Aberto do...

Mai 27, às 21:42

Discovery

Google celebra a vida de Evelyn Ruth Scott AO com Doodle
O Doodle de hoje celebra a ativista social, educadora e defensora dos direitos indígenas australiana, Evelyn Ruth Scott AO. Durante a Semana Nacional da Reconciliação, homenageamos Evelyn, que lutou...

Mai 27, às 21:30

DEV

How to use Firebase Authentication in Next.js 13, Server Side with Admin SDK
I'm new to this world of Full Stack Frameworks like Next.js, SvelteKit, Remix... But I know all the advantages it has so I wanted to use it to create a project I'm working on. I love Firebase and I wanted to...

Mai 27, às 20:20