Sintaxe var – não precisamos de tipos no Java?

Sintaxe var – não precisamos de tipos no Java?

Fala meus queridos, estou voltando 😉

E já quero começar indo direto ao ponto.

Nesses dias me deparei com algumas dúvidas de “alunos” (que ajudo, dou dicas etc), sobre o uso do “var”. Para que serve? Porque vou utilizar isso? Tem vantagem? E a tipagem do Java? Etc

Então resolvi tentar explicar aqui de uma maneira simples (creio eu) para seu entendimento e deleite 😀

Bem, primeiro que essa “sintaxe” foi introduzida no Java 10 (Java 9 já tinha a ideia), como uma forma de melhorar a legibilidade do código e diminuir a verbosidade, e claro, para a galera que não gosta muito de se preocupar com tipos 😀 rsrsr.

Brincadeiras a parte, vamos tentar entender para que serve realmente isso…

Como já foi dito, a sintaxe var é uma novidade introduzida no Java 10 (hoje já estamos na versão 18), que nos permite a declaração de variáveis locais sem especificar o tipo de dados explicitamente. Em vez disso, o tipo dessa variável é inferido (injetado, definido) pelo compilador a partir do valor que você atribui.

Exemplo:

var nomeDaVariavel = valor;

Onde var é a palavra-chave que indica a declaração de uma variável com tipo inferido. O tipo aqui, é um tipo var.

Por exemplo, vamos supor que queremos declarar uma variável do tipo String e atribuir o valor “Olá, mundo!” a ela.

Sem uso da sintaxe:

String mensagem = "Olá, mundo!";

Com uso da sintaxe var:

var mensagem = "Olá, mundo!";

Nesse exemplo, o tipo da variável mensagem é inferido automaticamente pelo compilador como String, com base no valor atribuído a ela, ou seja, a sua variável mensagem vai ser do tipo que você declara no seu valor/referência.

Podemos usar isso para qualquer contexto em que seja possível inferir o tipo de dados da variável a partir do valor atribuído a ela. No entanto, é importante notar que a variável declarada com var deve ser inicializada na sua declaração.

Ué, mas porque eu usaria isso? Porque em uma linguagem fortemente tipada como o Java, vou querer trabalhar com o var?

Exatamente por isso querido(a) Padawan, por ser uma linguagem fortemente tipada, tem suas vantagens e desavantagens, e é ai onde entra algumas vantagens de não deixar explícito a tipagem:

1 – Redução de código: Você pode declarar uma variável com menos código, o que pode tornar o código mais conciso e legível. A galera do “quero escrever menos” pira :D:

String nome = "João";

List<Integer> numeros = new ArrayList<Integer>();

Usando a sintaxe var, você pode escrever o mesmo código com menos código:

var nome = "João";

var numeros = new ArrayList<Integer>();

2 – Tipos longos ou complexos: Em alguns casos, o tipo de dados de uma variável pode ser longo ou complexo, tornando a especificação explícita um pouco mais difícil de ler de escrever e de lembrar rsrsr. Nesses casos, usar a sintaxe var pode tornar o código mais fácil de ler e manter. Por exemplo:

Map<String, List<Pair<String, Integer>>> mapa = 
             new HashMap<String, List<Pair<String, Integer>>>();

Usando a sintaxe var, você pode simplificar a declaração da variável:

var mapa = new HashMap<String, List<Pair<String, Integer>>>();

3- Refatoração de código: Esse com certeza é o mais interessante. Usar o var pode facilitar a refatoração do seu código, pois você pode alterar o tipo de dados da variável sem ter que atualizar todas as referências à variável no código :D. Por exemplo, considere o seguinte código:

List<String> nomes = obterNomes();

Se você decidir mudar o tipo da variável para ArrayList<String>, terá que atualizar todas as referências à variável no código. No entanto, se usar o var, poderá alterar o tipo de dados da variável sem se preocupar em atualizar as referências da variável:

var nomes = obterNomes(); // Não é necessário atualizar as referências da variável

Acho que já ficou bem claro né?

Mas, vamos ver mais alguns exemplos utilizando a sintaxe var:

Em loops

Sem sintaxe var:

for (int i = 0; i < motos.size(); i++) { 
     Moto moto = motos.get(i); 
     // ... 
}

Usando o foreach:

for (Moto moto: motos) { 
     moto.getNome(); 
     // ... 
}

Com sintaxe var:

for (var moto : motos) { 
     moto.getNome(); 
     // ... 
}

Declaração de variáveis em expressões lambda:

Sem sintaxe var:

Function<Moto, String> formatador = new Function<Moto, String>() {
    public String apply(Moto moto) { 
           return moto.getMarca() + " " + moto.getModelo(); 
    } 
};

Com sintaxe var:

Function<Moto, String> formatador = 
                       (var moto) -> moto.getMarca() + " " + moto.getModelo();

Declaração de variáveis em coleções:

Sem sintaxe var:

List<Moto> motos = new ArrayList<>();

Com sintaxe var:

var motos = new ArrayList<Moto>();

Como podemos ver, o uso da sintaxe var pode simplificar bastante o código, reduzindo a verbosidade e tornando-o mais fácil de ler. Além disso, a sintaxe pode ajudar a reduzir erros de digitação e tornar o código mais seguro, já que a inferência de tipo é feita pelo compilador.

Pode parecer pouco ou besteira, mas ajuda muito a produtividade do dia a dia.

No entanto, é importante lembrar, ela não deve ser usada em excesso e no geral, é usá-la apenas quando o tipo da variável é óbvio a partir do contexto, ou quando o tipo é irrelevante e o objetivo é tornar o código mais conciso.

Em geral, devemos usar o var sempre que tornar o código mais claro e legível, sem comprometer a clareza ou a segurança. E devemos lembrar que não pode ser usada para declarar parâmetros de método ou variáveis de classe.

Em alguns casos, é melhor especificar explicitamente o tipo de dados da variável para tornar o código mais fácil de entender e manter, afinal, estamos falando do Java, que foi criada fortemente tipada e tem um objetivo claro para isso.

Então é isso, como deu para perceber, é muito simples trabalhar com a sintaxe var e seu uso tem suas vantagens e desvantagens. Espero que tenham entendido o porque e para que do seu uso e até a próxima.

Antes que eu esqueça, você já usa o var no seu código? Deixa ai um comentário 😉

33 Comments on “Sintaxe var – não precisamos de tipos no Java?

  1. Boa, nem sabia que o java tinha isso, bem legal. depois vou tentar fazer alguma coisa utilizando esse var. Paranbens pelo pos, e continue assim. <3

  2. All rights reserved. Need it today? Get it today with Buy Online, Pick Up In-Store or Same Day Delivery. HairBlond, Straight, Medium MAC CosmeticsEye Brows Styler-Brunette Free Shipping* and Returns – Click & Collect available. I went through several MAC Spiked eye brow pencils in the past and really liked them. Will check this new formula out. What are you using to make your hair so shiny and healthy looking Karen? Your hair looks great! Shipping offer valid on orders shipped to US addresses. Free Standard Shipping and Returns* with any purchase. Upgrade to 2nd Day Shipping for $5.00 or Overnight Shipping for $10.00. Standard Shipping is always complimentary on MAC Gift Cards. No offer code necessary. Shipping offer not applicable to Pro members. Place order prior to 3:00 PM EST for same day processing. Please note, due to the volume of orders, processing may take 1-3 business days.
    https://headwatersdiscgolf.com/forums/users/9383dccclii1409/
    There is an Ulta rewards membership program that you can sign up for at ulta.com. The Ulta Rewards program lets you earn points for every dollar spent on their store. You can later redeem these points for discounts on your Ulta products or beauty services. Ulta offers a 20% coupon code for your first order once you sign up to get an Ultamate Rewards credit card. Sign up today and watch your inbox for an exclusive promo code. You also receive 2X points on orders placed online. Don’t Miss Out! Join our large community of insiders – it’s totally free! Once you join, you’ll be able to save & share your favorite deals, rate posts and recipes and add items to your HipList and Cookbook! What are ya waiting for?! Copyright 2023 by Capitol Broadcasting Company. All rights reserved. This material may not be published, broadcast, rewritten or redistributed.

  3. I personally love a great neutral pallet and this Ulta brand set had all the matte and shiny colors I use daily and for a night out. Ulta Beauty 1349 Coolidge Hwy (Maple) As part of delivering that perfect look, you’ll: Write a Review My friend gets them threaded and I was interested in that – Im just afraid they will make them too thin. Legs, underarms, and Brazilian waxes don’t exactly require much shaping; many cases like a closeout sale everything must go. That isn’t the case with our eyebrows, though, as they serve to frame our eyes and face. This wax kit stands out for its all-natural, organic sugar-wax formula. Sugar wax is not only a great natural alternative to conventional wax, but it’s also known to be gentler on the skin, have longer-lasting results, and result in less pain than other waxes.
    https://queriesanswer.com/community/profile/lawannacarper68/
    This multi purpose tool protects your upper and lower eyelids from mascara smudges and also prevents mascara clumps on your eyelashes. $0.50 Make the Most out of Your Mascara Wand Thank you for supporting our journalism. You can subscribe to our print edition, ad-free app or electronic newspaper replica here. Q-Tips Lightly hold a Q-Tip vertically against your eyelashes and brush your mascara upwards. Any mascara bits will be brushed onto the Q-Tip. Do the same for the lower lashes. To find out about how we use your information please visit our Privacy Notice Perfect as gifts for your lash crew or to add to a lashcare kit for your clients. There is no evidence to support the tale that a 19th century London prostitute invented false eyelashes. Canadian inventor Anna Taylor patented false eyelashes similar to those worn today in 1911. We rate this claim FALSE.

  4. Choosing the right games to play at your long-distance baby shower is important. These online baby shower games you choose to play should not only get all your guests involved but also give them the opportunity to enjoy such a unique experience. With the help of the WebBabyShower platform, this will be as easy as 1-2-3. Get everyone in your online party to download Psych, and let the fun begin. Each player makes up fake answers to real trivia questions, and it’s your job to find out the real answer. It’s from the same creators of Heads Up!, so you get an idea of what type of fun is in store. You’ll be able to play over your phone for this one, so don’t worry if your Zoom connection is lacking. Scattergories is not as well known as the other options on this list, but this multiplayer game is a cult classic in some gaming circles. Gameplay all revolves around a template sheet with a series of general clues and categories. Players must use a preselected letter of the alphabet (this letter changes every round) to start each answer to the given clues. A timer adds a little pressure to mix. As for tackling online Scattergories via Zoom, people have a couple of options.
    http://www.aldea.co.kr/board/bbs/board.php?bo_table=free&wr_id=113798
    Though Nintendo did not provide an official date as of yet, the first two titles in the series (Mario Party and Mario Party 2) are coming to the Nintendo Switch Online + Expansion pack library until the end of 2022. Mario Party 3 should be released sometime in 2023, according to the reveal stream. If you select Friends, connect to the internet, and then progress through the menus until you are given an overview of the Toad village. Pick the Friend House on the left to open up the online menu where you can either create a room or join a lobby. From here, you will be given options such as changing who can join your lobby and if those people will require a password to join. For those wanting to play with random people, just select Open to All and No Code. Inversely, if you’re joining a friend, select the Join Room tab, which lets you look for your buddy’s lobby.

  5. Глубинный регенеративный массаж лица — это уникальная методика, которая помогает освободиться от глубокого напряжения и блоков, которые образуют на лице. Вакуумно-роликовый массажер улучшает обмен веществ кожи улучшает лимфатический отток ускоряет релаксацию избавляет от целлюлита. Gess Star Face Pro еще один эффективный прибор для массажа лица и ультразвуковой чистки. Для комплексного ухода за кожей были предусмотрены 3 скоростных режима. Массажер подходит для домашнего и салонного использования. Эффективности применения удалось достичь за счет ультразвуковых волн. Подходит для всех типов кожи. Работает от аккумулятора. Для домашнего использования отлично подходят стеклянные вакуумные банки для лица. Как говорилось выше, все массажеры для лица направлены на улучшение внешнего вида за счет расслабления лицевых мышц и улучшения обменных процессов в тканях. Среди отличий можно выделить два основных:
    http://plaworld.kr/bbs/board.php?bo_table=free&wr_id=37736
    Ведущий 2. Сегодня в зале присутствуют те, для кого спорт стал неотъемлемой частью жизни. (Концертный номер — ПЕСНЯ. Выходят ведущие.) Профессиональный ведущий праздника умеет объединять за одним столом разных людей. Это человек с хорошим чувством юмора. Как бы хорошо праздник не был продуман, все может пойти не по плану, и профессиональный ведущий всегда готов к импровизации. Позитивный настрой, полезная информация, анонсы и интерактивы – как удержать внимание слушателей комментариями, объясняет радиоведущий, заведующий учебной частью «Школы Радио» Эдуард Костюков. Не только на шоу КВН бывают смешные представления. Шуточная сценка или юмористический номер может стать частью концертной программы или праздничного сценария. Перед номером юмористического жанра ведущий произносит соответствующую подводку. Мебка ТВ Запись подводки

  6. Gama Casino – настоящий рай для любителей азарта. Здесь я нашел все, что искал: увлекательные игры, щедрые бонусы и безопасную игровую среду. Регистрация была простой и быстрой, и в течение нескольких минут я был готов к игре. Отличное качество графики и звука добавляют атмосферности в игровой процесс. Я безусловно рекомендую Gama Casino всем азартным любителям!
    Больше на сайте https://omega-plaza.ru/

  7. Mwen te swiv yon bon konsèy nan yon forum sou entènèt epi mwen te jwenn sit sa a ki te rekòmande nan li. Mwen te enterese nan li paske mwen te vle jwe nan https://1x-bet.fun/ nan Ayiti epi mwen te pa konnen kijan pou mwen fè sa. Men, lè mwen te jwenn sit sa a, mwen te kapab fasilman enskri ak yon kont nan 1xbet epi mwen te kòmanse jwe. Mwen te gen chans lanmò, paske mwen te kapab genyen 127 dola nan jwèt la. Mwen kontan anpil ak sèvis sa a epi mwen rekòmande li bay tout moun ki vle jwe nan 1xbet nan Ayiti.

  8. Я решил попробовать свою удачу в кэт казино и был приятно удивлен процессом регистрации. Всего за несколько минут я заполнил необходимую информацию и получил свой аккаунт. Теперь я готов наслаждаться игрой и выигрывать в Cat Casino!

  9. Я впечатлен сервисом Cat Casino! Играю здесь уже несколько месяцев, и каждый раз получаю максимум удовольствия от разнообразных игр и щедрых бонусов. Кэт Казино действительно знает, как радовать своих игроков!”

  10. Sex toys https://self-lover.store/ have become an integral part of modern intimate life for many people. Their variety strikes the imagination. In intimate goods stores you can find many different types and models that help diversify your sex life and give pleasure.

  11. ยูฟ่าเบท789 เว็บแทงบอลที่ใหญ่ และการเงินมั่นคงที่สุด สล็อตออนไลน์ ไม่มีขั้นต่ำ ใช้ทุนน้อย เล่นได้ทุกเกม

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

*

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.