RUVIDEO
Поделитесь видео 🙏

Null Safety in Kotlin - Kotlin Tutorial

📁 Обучение 👁️ 16 📅 30.11.2023

Null Safety in Kotlin is a free tutorial by Peter Sommerhoff from Kotlin course
Link to this course(Special Discount):
https://www.udemy.com/course/kotlin-android/?ranMID=39197&ranEAID=Gw%2FETjJoU9M&ranSiteID=Gw_ETjJoU9M-WOKWSoM9m8cj058GW.HyKA&LSNPUBID=Gw%2FETjJoU9M&utm_source=aff-campaign&utm_medium=udemyads
This is the best Kotlin Course
Course summary:
Write clean code with Kotlin
Avoid ceremony and boilerplate code around Android APIs
Use functional programming to write concise, expressive code
Create Android apps with Kotlin
Write readable SQLite transactions using extension functions in Kotlin
Use the Kotlin Android Extensions to avoid findViewById()
Create multiple activities, layouts and menus
English
Narrator: Alright, now in this lecture we're gonna take a look at one of the major differences in Kotlin when compared to Java. Now more specifically we're gonna talk about nullable types and explicit nullable types. So in Kotlin by default, every type is not nullable which means you can not assign null to it. So let's say we want to create a variable, or let's say a value string and we want this of type String, that in Java you could just assign null to it, which would be fine and would actually be valid for the type String. But you can already see here that we have a red mark, and if I try to run this line, so it's gonna have these squiggly, red lines here, and if I hover over the mark here, over the red mark, it says that null can not be a value of a non-null type String. So this means whenever you have a variable of type String, you can be sure that you never have a null in there. So as long as you're working with normal data types like this, you also can never have a null pointer exception, unless you're interfacing with Java code, which can of course throw null pointer exceptions. So now of course the question is what if you do wanna use null in your code because, well let's say, for some reason you can't avoid it. Well what you can do then is you can say val string, and this should be of type String, but this time nullable and to do this, you put a question mark behind the data type that you wanna use, and then you can also assign null to it. So String question mark is basically the data type, the nullable String data type, which can be any String or null. Now, notice that this holds for every data type in Kotlin. So remember that even integers and doubles are also objects in Kotlin. So you can't assign null to this one, but if you do put a question mark behind the int data type, you can assign null to it. Now, of course the problem with having nulls in your code is that maybe at some point in your code where you're not even sure anymore that an object is null, you try to access a property or a method on that object. So let's say you want to have the length of the string, but that's not gonna work because there's actually no string stored in that object. So you can not call, or you can not get the length of the string. So here in this case, Kotlin is not actually gonna give you a null pointer exception. But what it's gonna do is the compiler's already gonna see that this is invalid. So already at compile-time, which is very important, Kotlin is gonna tell you that this is not valid because you have a nullable type here. So it's unsafe to call any method or property on this object. Now there are two things you can do. So to do it the Java way, which is the better way in this case, is to put two exclamation marks here, and then just call length, or whatever else you wanna have, and that's gonna give it a Kotlin null pointer exception. Now, what string exclamation mark exclamation mark does is it tells the compiler that you're sure that the string object is not gonna be null, and it's your fault if it is indeed null, and you are just wrong at this point. And notice that the double exclamation mark here basically looks like you're screaming at the compiler and this intentional because you shouldn't use this unless you're really sure about this or you it's really necessary, but it's normally not. So let's look at the better way to do this which is the so-called safe call operator. And this is, by the way, the unsafe call operator. So to safely call any method or property on this object here what we're gonna do is we're gonna put a question mark here and then access, well for example, the length. Now in this case, when the object here is null, this is just gonna return null. But in the other case, where let's say string is of type String nullable, but it is indeed not null, but contains some kind of String, so let's say Peter. Then when you call safely the length here, using the question mark, then it's just gonna return the length of the string. So basically this is like an if-then-else. So if the object here is null, then any call you do here is just gonna return null. But if the object is actually not null and has a valid value, then it

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Null Safety in Kotlin - Kotlin Tutorial», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.