- Android studio kotlin switch case
- Как реализовать оператор switch-case в Котлине
- 6 ответов
- Create a Switch in Kotlin Programmatically
- Activity XML Layout File
- Switch UI Component Example in Kotlin
- Switch in Kotlin
- Different attributes of Switch widget
- Adding Switch code in activity_main.xml file
- Replace Switch with When in Kotlin
- switch
- More features of when
- Conclusion
Android studio kotlin switch case
Статья проплачена кошками — всемирно известными производителями котят.
Если статья вам понравилась, то можете поддержать проект.
У Kotlin есть ключевое слово when, которое заменяет оператор switch и позволяет делать более сложные вещи. Выражение when имеет больше возможностей, чем классический switch и позволяет использовать объекты.
Допустим, мы хотим создать мнемоническое правило для цветов радуги: Кот-охотник желает знать, где сидят фазаны.
В примере мы создали функцию, которой присвоили значение, возвращаемое when. В Java мы так не можем писать. Нам пришлось бы создавать отдельный блок кода switch, не связанный с каким-то методом. В Kotlin такой вариант также возможен при желании.
Вам не нужно использовать break, как в Java. Для комбинирования разных веток используйте запятые.
В примере используются укороченные имена цветов из перечисления Color. Перечисление вынесено в область импорта.
Вместо перечислений можно использовать и обычные переменные.
В примере используется ключевое слово else, который является аналогом default и ему передаётся значение, когда ни одно из выражений не выполнится.
Например, мы можем отслеживать видимость компонента ImageView.
В предыдущих примерах возвращаемый результат присваивался функции или использовался сам по себе. Также можно присвоить и обычной переменной.
В выражении when можно использовать ключевое слово is для проверки принадлежности к экземпляру класса.
Источник
Как реализовать оператор switch-case в Котлине
Как реализовать эквивалент следующего кода оператора switch Java в Kotlin?
6 ответов
Вы могли бы сделать так:
Когда выражение, когда заменяет оператор переключения C-подобных языков. В простейшем виде это выглядит так
когда аргумент совпадает со всеми ветвями последовательно, пока не будет выполнено какое-либо условие ветвления. когда можно использовать как выражение или как выражение. Если оно используется в качестве выражения, значение удовлетворенной ветви становится значением всего выражения. Если он используется в качестве оператора, значения отдельных ветвей игнорируются. (Как и в случае с if, каждая ветвь может быть блоком, а ее значением является значение последнего выражения в блоке.)
Вот пример, чтобы знать, используя «когда» с произвольными объектами,
VehicleParts — это перечисляемый класс четырех типов.
mix — это метод, который принимает два типа класса VehicleParts.
setOf (p1, p2) — выражение может дать любой объект
setOf — это стандартная библиотечная функция kotlin, которая создает Set, содержащий объекты.
Набор — это коллекция, для которой порядок предметов не имеет значения. Kotlin разрешено комбинировать различные типы, чтобы получить множественные значения.
Когда я прохожу «Parts Parts.TWO» и «Parts». «КОЛЕСО», я получаю «Велосипед». Когда я проезжаю VehicleParts.FOUR и VehicleParts.WHEEL, я получаю «Автомобиль».
Корпус переключателя в kotlin очень гибкий
Просто используйте ключевое слово когда . Если вы хотите сделать цикл, вы можете сделать так:
switch в Java фактически when в Котлине. Синтаксис, однако, другой.
Вот пример различных применений:
Большинство из них компилируется в switch , кроме when < . >, который компилируется в серию операторов if.
Но для большинства случаев, если вы используете when(field) , он компилируется в switch(field) .
Однако я хочу отметить, что switch(5) с кучей веток — просто трата времени. 5 всегда 5. Если вы используете switch , операторы if или любой другой логический оператор в этом отношении, вы должны использовать переменную. Я не уверен, является ли код случайным примером или это фактический код. Я указываю на это в случае, если это последнее.
Источник
Create a Switch in Kotlin Programmatically
In this short Kotlin programming tutorial we will learn how to create a Switch in Kotlin programmatically. In the code example below we are going to cover:
- Create Switch and add it to a LinearLayout
- Get input from the Switch when it’s state is changed
- Set textOff and textOn text programmatically
- Set OnClickListener on the Switch so that we can handle state changes event
Activity XML Layout File
Following is the Activity_switch_example .xml containing an empty LinearLayout to which we will add the Switch .
Switch UI Component Example in Kotlin
Below is Kotlin code example which demonstrates how to create and add a Switch UI component to our app activity programmatically. It also shows how to set onClickListener and handle events when user taps on the Switch component to change its state from On to Off and back from Off to On.
If you run the above code example in Android studio you should the the following view:
I hope this example was helpful!
If you are looking for more code examples in Kotlin or even longer step by step Kotlin tutorials, checkout the Android->Kotlin category of this blog.
And if you are looking for books or video tutorials on Kotlin check the list of resources below. I hope you will find some of them helpful!
Источник
Switch in Kotlin
Android Switch is also two-state user interface element which is used to toggle between ON and OFF as a button. By touching the button we can drag back and forth to make it either ON or OFF.
The Switch element is useful when only two states require for activity either choose ON or OFF. We can add a Switch to our application layout by using Switch object. By default, state for the android Switch is OFF state. We can also change the state of Switch to ON by setting the android:checked = “true” in our XML layout file.
In android, we can create Switch control in two ways either in using Switch in XML layout file or create it in Kotlin file dynamically.
First we create a new project by following the below steps:
- Click on File, then New =>New Project.
- After that include the Kotlin support and click on next.
- Select the minimum SDK as per convenience and click next button.
- Then select the Empty activity =>next =>finish.
Different attributes of Switch widget
XML Attributes | Description |
---|---|
android:id | Used to uniquely identify the control. |
android:gravity | Used to specify how to align the text like left, right, center, top, etc. |
android:checked | Used to specify the current state of switch control. |
android:thumb | Used to set drawable to be used as thumb that can be moved back and forth. |
android:thumbTint | Used to set tint to apply to the thumb. |
android:text | Used to set the text of the Switch. |
android:textOn | Used to set the text when toggle button is in ON (Checked) state. |
android:textOff | Used to set the text when toggle button is in Off (unchecked) state. |
android:textStyle | Used to set style of the text. For example, bold, italic, bolditalic etc. |
android:textColor | Used to set color of the text. |
android:textSize | Used to set size of the text. |
android:background | Used to set background color of the toggle button. |
android:drawableBottom | Used to set drawable to the bottom of the text. |
android:drawableLeft | Used to set drawable to left of the text. |
android:drawableRight | Used to set drawable to the right of text. |
android:padding | Used to set the padding from left, right, top and bottom. |
Adding Switch code in activity_main.xml file
In this file, we will use the LinearLayout and two switches inside it. Set the attributes of each switch like switch id, text etc.
Источник
Replace Switch with When in Kotlin
Hello World! If you are reading this blog, then you must be a programmer and you know how to code in particular programming language. I mean to say that you must be familiar with at least one of the programming languages and know about the basics syntax and elements used in any programming languages like conditional statements, looping structures, functions, etc.
In this blog, we will look upon the replacement of switch with the when keyword. Firstly, we will look on to some examples of switch and after that, we will look at how the when keyword makes our task or code easier and more understandable. So, let’s get started.
switch
If we are using some conditional statements and the condition used in the conditional statements are applied on similar type of data, then instead of having a vast or big code for the conditional statement, we can use switch to avoid using so many conditional statements in our code.
For example: below is an example of a conditional statement used to print the word representation of numbers:
So, in the above code in order to print the numbers in word, you have to use various conditional statements and this results in a large number of lines of code. Think of a situation when you have to print the words representation of numbers up to 100 or 1000. If you are using conditional statements then you have to use 1000 conditional statements.
To remove this difficulty, switch-case was introduced, where we pass the variable to be compared with-in the switch statement (in our example, that variable is number) and compare it with various case statements present corresponding to it and do the operation. So, the switch-case version of the above code will be:
In the above code, number is passed in switch statement and cases are used to compare that number. For example, if the number is 1 then case 1 will be executed, if number is 2 then case 2 will be executed and so on. But if the number is not equal to any of the case present then the default block will be executed.
This is a very convenient way of using conditional statements. But many programming languages like Python doesn’t use the switch-case. They have some different and better way of using the conditional statements except switch. In Kotlin we use when in place of switch. So, let’s move on and try to find how we can replace switch with when?
So, if you are moving from Java to Kotlin, then you will find some changes in the syntax part also. In Java we use switch but in Kotlin, that switch gets converted to when. when is also used for conditional representation but it does the things in a very smarter and easier way. Whenever you are having a number of possibilities then you can use when in your code.
For example, the above code that was written using switch gets converted to something like below after using when:
In the above code, like in switch, the number is passed in when and then we compare that number with various options available. In our case, if the number == 1, then “one” will be printed and so on. If more than one match is found then the match that occurs first will be considered only. If no match to the number is found then the else part will be executed.
Also, there is no need of that else part if you are sure that your code will never code to the else part in any situation. For example:
In the above example, the variable noElseChecking is assigned true. After that, we are checking that variable in when block. The idea here is that either the value of the noElseChecking variable will be true or false and there is no third case. So, if we handle these two case then there is no need of else part in when because if we use else then that code will be unreachable code.
More features of when
Till now, we have a basic idea of how when can be used to replace switch in Kotlin. Let’s look upon some more features of when that makes it a good to have in any Kotlin code:
- Two or more choices: While using the switch statement, we can check or compare with the value passed in switch in one case at a time, but in when we can apply more than one choice. For example:
In the above example, the second statement says that if the value of number will be 2 or 3 then the code will print “Two or Three”. Here we are having more than one choice.
- Condition branch: You can apply conditions in any branch of when statement and the body of that statement will only be executed when the condition is satisfied. For example:
In the above example, if you pass number == 6 then the output will be “Number between 4 and 8”. But there is one doubt, as the number is 6 then statement 4 and 5 are true then why only statement 4 is executed? If you are reading this blog with full concentration then you know the reason behind this because it is discussed in the introduction to when section. The reason behind this is, if more than two statements are correct then the statement appeared first will be used and other true statements will be discarded.
- «when» without arguments: You can use when without any argument also i.e. simply write when and in the block or body of the when write some conditional statement. A when without an argument is like applying some conditional statements. For example:
In the above example, there is no argument passed in when, so, you can use conditional statement inside when by using the variables used in the code.
- Any type passed in «when»: You can pass any type of variable in when i.e. you can pass integer or string or character in when at a time. This facility was not there in switch, there if you are passing an integer value then your case must be an integer value otherwise you will get an error. But when you can use any type as below:
In the above example, the same object obj is used to compare with the integer value, then with the string value then it is checked for long and so on.
- Smart casting: You can perform smart casting i.e. automatic casting if you are using an is expression in your when block. For example:
Conclusion
In this blog, we learned how to use when in place of switch in Kotlin. We saw that, if we are having a number of possibilities for a particular variable then we can make use of when to handle all the possibilities. Also, we can use when for multiple or more than one choices.
Источник