Learning the first series: KOTLIN Introduce
Repo : https://github.com/JetBrains/kotlin
What will i learn?
Kotlin is a programming language that runs on top of JVM (Java Virtual Machine) and can also be compiled into Javascript. Kotlin was developed by JetBrains.
At the Google IO'17 event yesterday, Kotlin was officially supported as the language for Android app development and will begin to be used on Android Studio 3.0.
Kotlin is considered easier and fun than Java, because the syntax is simpler.
Immediately we will learn:
- Coding Functional Android Apps in Kotlin
- Getting Started Use kotlin
- Understand the syndrome of cotlin
- kotlin android extension: Wave goodbye
FindViewById
Requirements
- Modern computers running macos, Windows or UbuntuConnections
- decent internet to download Anaconda Distribution (large)
- Ambition to learn Python programming
Why choose kotlin?
Here are some points that support why kotlin become one of the modern programming languages and can develop Android applications, including:
Compatible => Kotlin is compatible with JDK 6, Kotlin support runs on Android Studio and is compatible with Android System
Performance => using lambdas on the kotlin makes it faster with code written in java.
Interoperability => Support the use of Android libraries in kotlin apps. You can also use the code in the kotlin and java languages simultaneously on a projectEasy Learning
Curve => It should be a good programmer to play on Java Android will not be so difficult when switching to the programmer kotlin, because rada-rada similar
Difficulty
- Basic
In this follow-up tutorial, we'll start with the actual development of Kotlin. By the time you reach the end of the tutorial, you'll create a simple Android app featuring a list of texts - and written entirely in Kotlin. You'll also know how to avoid having to write another FindViewById
, by utilizing the Kotlin Android extension.
But first, it's time to teach our development environment how to speak a new language!
Installing Kotlin Plugin on Android Studio
The first thing you need to do is to add Kotlin support to your Android Studio installation.
Before you start, make sure you're running the latest version of Android Studio, stable, as you're more likely to encounter bugs with Kotlin plugins on an experimental version of Android Studio. It's also worth opening the SDK Manager and checking whether updates are available for any packages you install.
Once you're sure that your development environment is up-to-date, you're ready to install the Kotlin plugin. Launch Android Studio and you'll see the Welcome to Android Studio window - if this window does not appear, close Android Studio completely and relaunch.
Give the Configure icon a click, then select Plugins from the next dropdown.
Click Install JetBrains plugin ... button.
Select Kotlin from the menu, then click the Install green button. You have to restart your IDE before the Kotlin plugin becomes active, so click the Restart Android Studio button that pops up or restarts your IDE manually.
Configure Your Project to Use Kotlin
At this point, your IDE can understand and run the Kotlin code, but you still have to configure Kotlin every time you want to use it in a new project. Let's create a new project and configure the project to use Kotlin now. Create a new project with your preferred settings, but for simplicity's sake, choose Empty Activity when prompted.
Thanks to the Kotlin plugin, configuring the project to use Kotlin could not be simpler: just select Tools from the Android Studio toolbar, followed by Kotlin and Configure Kotlin in Project.
This will open a popup where you can choose to configure Kotlin to:
- all modules
- all modules containing Kotlin files
- or a single module named
Since I will only use Kotlin code in my project, I choose All modules. You can also choose which version of Kotlin you want to use - typically, this will be the latest version.
Or, you can configure Kotlin by selecting Help from the Android Studio menu bar, followed by Find Action ... In the Find Action Bar, start typing Kotlin Configuration at Project, then select this option when it appears.
The Configure Kotlin in Project option makes a number of tweaks to your project file build.gradle, so let's take a closer look at how these files have changed. Open your project's build.gradle file - it should look like this:
buildscript {
//Declares the version of Kotlin that you’re using. You’ll notice that the version of Kotlin is mentioned in both the buildscript classpath and in your project’s compile dependencies - the version number must be the same in both places//
ext.kotlin_version = '1.0.5-2'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
//Declares the Kotlin Gradle plugin as a classpath dependency//
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
}
}
Now, let's look at the file build.gradle your module level:
apply plugin: 'com.android.application'
//Applies the Kotlin Android plugin//
apply plugin: 'kotlin-android'
android {
compileSdkVersion 25
buildToolsVersion "24.0.0"
defaultConfig {
applicationId "com.jessicathornsby.kotlinexample"
minSdkVersion 21
targetSdkVersion 25
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
//Although Gradle will compile any Kotlin files it finds in src/main/java, it’s good practice to store your Kotlin files in a dedicated Kotlin directory. Here, you can see that the Kotlin plugin has added a src/main/kotlin declaration to build.gradle, but note that it hasn’t actually created this directory, so we’ll create it ourselves later in this article//
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.1'
testCompile 'junit:junit:4.12'
//Adds the Kotlin Standard Library as a project dependency//
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
repositories {
mavenCentral()
}
Finally synchronize your changes by clicking Sync Now from the popup that appears or by clicking Sync Project with icon Gradle File on the Android Studio toolbar.
Converting Java Files to Kotlin
One Kotlin plugin feature that is particularly useful for Kotlin's newcomers is its ability to convert Java source files to Kotlin, while maintaining full runtime compatibility.
Being able to see exactly how each Java file will be translated into Kotlin is ideal to help you learn the language, but it can also come in handy throughout your Kotlin trip- if you ever struggle to figure out how to write something in Kotlin, you can always write it in Java and then use this feature to convert that code into Kotlin.
Let's convert our MainActivity project files into Kotlin source files. There are two ways to invoke the Java Converter Plugin to Kotlin Files, so:
- Choose your MainActivity file, then choose Code from Android Studio's menu bar, followed by Convert Java File to Kotlin File
- Or choose Help from the Android Studio menu bar, followed by Find Action. In the next popup, start typing Convert Java file to Kotlin file and then select this option when it appears. Note that you can also launch the Find Action popup with keyboard shortcuts: if you're using a Mac, press the Command-Shift-A key, and if you're using Windows or Linux, then press Control-Shift- A.
Know that, depending on the complexity of your code, conversions may not always be 100% accurate, so you should always check the conversion code for errors.
Your newly-converted MainActivity will look like this:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
You will also notice that the file extension has changed, changed from MainActivity.java to MainActivity.kt.
It may be simple Activity
, but some of these lines illustrate some of the key characteristics of Kotlin syntax. Since this is our first look at some actual Kotlin code, let's select this class separately line by line.
Understanding Kotlin Syntax
In Kotlin, you declare the class uses the keyword class, just like in Java. However, in Kotlin, classes (and methods) are public and final by default, so you can create a class just by writing class MainActivity.
When it comes to expanding the class, you replace Java extends with a colon, and then attach the parent class name. So in the first line of our MainActivity.kt file, we create a general class, called MainActivity which extends: AppCompatActivity
class MainActivity : AppCompatActivity() {
Equivalent to Java is:
public class MainActivity extends AppCompatActivity {
If you want to replace a class or method, then you must explicitly declare it as open or abstract.
In Kotlin, a function is defined using funkey keywords, followed by function names and parameters in brackets. In Kotlin, the function name exists before the type:
override fun onCreate(savedInstanceState: Bundle?) {
This is the opposite of Java, where type comes before the name:
public void onCreate(Bundle savedInstanceState)
Note that we do not specify that this method is final, because in Kotlin all methods are final by default.
The rest of this activity looks very similar to Java. However, some of these lines illustrate other key characteristics of Kotlin:
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
In Kotlin, you do not need to finish the line with a semicolon, therefore there is no colon in the above snippet. You can add a colon if you really want to, but your code will be cleaner and easier to read without them.
Now that we have interpreted our MainActivity.kt file, let's move it to the proper home. Since Kotlin plugin has a problem with adding the src / main / kotlin declaration to our build.gradle file, let's actually create this directory. This step is not mandatory, but storing your Kotlin file in a special directory will make the project cleaner.
In Project Explorer Android Studio, Control-click main project directory and select New from the menu that appears, followed by Directory. Name this directory kotlin and then click OK.
If you're having trouble finding your project's main directory, open the little dropdown at the top left of Project Explorer ** and select Project. You should have no problem locating the elusive src / main directory
After creating a special Kotlin directory, drag your MainActivity.kt file into it. Be sure to retain your existing MainActivity.kt package file name to keep your project running.
Also, if you're just going to use Kotlin in this project, then you might want to remove the Java directory, rather than messing up your project with empty and unnecessary directories.
Because Kotlin compiles for bytecode, the app written in Kotlin feels exactly the same as the app written in Java, so try installing this app on your compatible Android device or AVD - it should feel as if nothing has changed.
Creating Extra Kotlin Files
If you continue to work with Kotlin in your project, then sooner or later you will need to start creating new Kotlin files rather than just changing the ones in Java.
To create a Kotlin file, Control-click your / src / main / Kotlin app directory and choose New> Kotlin Activity
Give your class a name and select class from the drop-down menu. Your new class will look like this:
class SecondActivity {
}
At this point, your activity is empty. To reach the point where you can start adding some real functions, you need to complete a few steps. First, add the import
statement you want to use. The only difference between the import statements in Kotlin and the import statements in Java is that you do not need to complete each row with a semicolon. As an example:
import android.app.Activity
import android.os.Bundle
import android.app.Activity
Next you have to specify an expanded class, using the same format as we see in our MainActivity.kt file:
class SecondActivity : Activity() {
}
Next, you need to change the Activity onCreate
method:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
You can now add whatever function you want to this Activity (and in the next section, I'll show you how to use Kotlin extensions to manipulate UI widgets, so this might be a good place to start), but one last bit of the settings you need finish is declaring your Kotlin Activity in your Manifest. It follows exactly the same formula by declaring a new Java Activity, for example:
<activity
android:name=".SecondActivity"
android:label="@string/second"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
Kotlin Android Extension: Goodbye wave findViewById
Now that we've mastered the basics, let's take a closer look at what Kotlin really can do - starting with a feature that can actually cut the amount of boilerplate code you need to write.
On Android, whenever you want to work with any View
in an Activity, you need to use thefindViewById
method to get a reference to the View
. This makes findViewById
one of the most important, but also one of the most frustrating bits of code that you will find yourself writing over and over, and more so in your Android project. The findViewById
method is a great source of potential bugs, and if you work with multiple UI elements in the same Activity, then everyonefindViewByIds
can really mess up your code, making it harder to read.
Although there are a number of libraries, such as Butter Knives, which aims to remove the need for findViewById
s, this library still requires you to annotate the fields for each Display, which can cause errors and still feels like a lot of effort would be Better to invest in other areas of your project.
Kotlin Android Extension Plugin (which was recently incorporated into the standard Kotlin plugin) promises to make `findViewById 'something from the past, offering you the benefits of the above mentioned libraries without the need to write additional code or send additional runtimes.
You can use the Kotlin extension to import a View
reference to your source file. At this point the Kotlin plugin will create a set of "synthetic properties" that allow you to work with this view as if they are part of your activity - most importantly, this means you no longer have to use findViewById
to search for eachView
before you can work with me t.
To use the extension, you must enable Kotlin Android Extension plugin in each module, so open your module ** build.gradle ** file and add the following:
apply plugin: 'kotlin-android-extensions'
Sync these changes by clicking on Sync Now .
You can then import a reference to one View
, using the following format:
import kotlinx.android.synthetic.main.<layout>.<view-id>
For example, if your acitivity_main.xml file contains an ID, then you will import a reference to this view by adding the following to: TextView
textView1
Activity
import kotlinx.android.synthetic.main.activity_main.textView1
You can then access textView1
in this activity using its own ID - and withoutfindViewById
look!
Let's look at the extension in action, by adding TextView
to our ** event_main.xml ** file, importing it into our ** MainActivity.kt ** file, and using the extension to programmatically set program text. TextView
Start by creating your TextView
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.jessicathornsby.myapplication.MainActivity">
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
You can then import your TextView
into ** MainActivity.kt **, and set the text using its ID only:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.myTextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myTextView.setText("Hello World")
}
}
Note, if you want to work with multiple widgets from the same layout file, then you can import the entire contents of the layout files in one motion, using the following formula:
import kotlinx.android.synthetic.main.<layout>.*
For example, if you want to import all the widgets from your activity_main.xmlYou file, then you will add the following to your Activity:
kotlinx.android.synthetic.main.activity_main.*.
Conclusion
In this second installment, we covered setting up your development environment to support Kotlin, and looked at how easy it is to convert your existing Java code into Kotlin. We also looked at some of the major characteristics of the Kotlin syntax, and introduced Kotlin Android extensions into our project.
In the third and final installment, we’ll look at some more advanced features of the Kotlin language that, as an Android developer, you should find especially useful.
Thank you for your contribution.
Your post content is actually plagiarized from external sources, as correctly indicated by cheetah bot below.
Plagiarism is a serious offense, and continuous abuse could lead to your permanent ban from utopian reviews.
Due to your low quality prior contributions, and this current contribution, you have been unfortunately banned for 60 days from utopian reviews.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]