Skip to main content

Questions tagged [kotlin]

Kotlin is a cross-platform, statically typed, general-purpose high-level programming language with type inference. This tag is often used alongside additional tags for the different targets (JVM, JavaScript, native, etc.) and libraries/frameworks (Android, Spring, etc.) used by Kotlin developers, if the question relates specifically to those topics.

Filter by
Sorted by
Tagged with
1103 votes
30 answers
575k views

What is the equivalent of Java static methods in Kotlin?

There is no static keyword in Kotlin. What is the best way to represent a static Java method in Kotlin?
pdeva's user avatar
  • 44.8k
1067 votes
29 answers
372k views

Place cursor at the end of text in EditText

I am changing the value of an EditText on keyListener. But when I change the text the cursor is moving to the beginning of the EditText. I need the cursor to be at the end of the text. How to move ...
Manu's user avatar
  • 10.7k
885 votes
23 answers
559k views

Unfortunately MyApp has stopped. How can I solve this?

I am developing an application, and everytime I run it, I get the message: Unfortunately, MyApp has stopped. What can I do to solve this? About this question - obviously inspired by What is a ...
nhaarman's user avatar
  • 100k
872 votes
8 answers
382k views

How to check if a "lateinit" variable has been initialized?

I wonder if there is a way to check if a lateinit variable has been initialized. For example: class Foo() { private lateinit var myFile: File fun bar(path: String?) { path?.let { ...
Mathew Hany's user avatar
  • 13.9k
860 votes
33 answers
469k views

Kotlin Ternary Conditional Operator

What is the equivalent of this expression in Kotlin? a ? b : c This is not valid code in Kotlin.
Drew Noakes's user avatar
787 votes
38 answers
271k views

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

When trying to run the Example CorDapp (GitHub CorDapp) via IntelliJ, I receive the following error: Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target ...
Joel's user avatar
  • 23k
612 votes
15 answers
424k views

How to make an Android device vibrate? with different frequency?

I wrote an Android application. Now, I want to make the device vibrate when a certain action occurs. How can I do this?
Billie's user avatar
  • 9,106
571 votes
19 answers
559k views

How to launch an Activity from another Application in Android

I want to launch an installed package from my Android application. I assume that it is possible using intents, but I didn't find a way of doing it. Is there a link, where to find the information?
Bastian's user avatar
  • 9,715
539 votes
8 answers
422k views

How to convert a Kotlin source file to a Java source file

I have a Kotlin source file, but I want to translate it to Java. How can I convert Kotlin to Java source?
activedecay's user avatar
  • 10.6k
498 votes
8 answers
242k views

Property initialization using "by lazy" vs. "lateinit"

In Kotlin, if you don't want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language reference): Lazy ...
regmoraes's user avatar
  • 5,369
472 votes
9 answers
118k views

What is the difference between "const" and "val"?

I have recently read about the const keyword, and I'm so confused! I can't find any difference between const and the val keyword, I mean we can use both of them to make an immutable variable, is there ...
Mathew Hany's user avatar
  • 13.9k
426 votes
13 answers
184k views

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

And the Kotlin newbie asks, "why won't the following code compile?": var left: Node? = null fun show() { if (left != null) { queue.add(left) // ERROR HERE } } Smart ...
frankelot's user avatar
  • 14.2k
425 votes
4 answers
138k views

How does the reified keyword in Kotlin work?

I'm trying to understand the purpose of the reified keyword. Apparently, it's allowing us to do reflection on generics. However, when I leave it out, it works just as fine. When does this make an ...
hl3mukkel's user avatar
  • 5,809
424 votes
65 answers
262k views

Duplicate class in Kotlin Android

I kept on getting an error that there is a duplicate error in classes. This is what I have under org.jetbrains.kotlin folder .idea/libraries It seems like the problem is because there is two different ...
midnighthowlers's user avatar
410 votes
27 answers
406k views

How to initialize an array in Kotlin with values?

In Java an array can be initialized such as: int numbers[] = new int[] {10, 20, 30, 40, 50} How does Kotlin's array initialization look like?
Lars Blumberg's user avatar
401 votes
6 answers
256k views

How do I initialize Kotlin's MutableList to empty MutableList?

Seems so simple, but, how do I initialize Kotlin's MutableList to empty MutableList? I could hack it this way, but I'm sure there is something easier available: var pusta: List<Kolory> = ...
ssuukk's user avatar
  • 8,370
401 votes
31 answers
206k views

What is the difference between var and val in Kotlin?

What is the difference between var and val in Kotlin? I have gone through this link: KotlinLang: Properties and Fields As stated on this link: The full syntax of a read-only property declaration ...
Akshar Patel's user avatar
  • 9,318
397 votes
10 answers
377k views

Alarm Manager Example

I want to implement a schedule function in my project. So I Googled for an Alarm manager program but I can`t find any examples. Can anyone help me with a basic alarm manager program?
Rajamohan Sugumaran's user avatar
391 votes
9 answers
286k views

How to get the current index in for each Kotlin

How to get the index in a for each loop? I want to print numbers for every second iteration For example for (value in collection) { if (iteration_no % 2) { //do something } } In java, ...
Adolf Dsilva's user avatar
  • 13.9k
390 votes
62 answers
495k views

A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution

All of sudden I start getting this error, and I am not getting idea why if anyone just let me know where this error is, will be enough helpful. As much I am able to get is this because of new update ...
Shubham Tater's user avatar
385 votes
15 answers
331k views

Constants in Kotlin -- what's a recommended way to create them?

How is it recommended to create constants in Kotlin? And what's the naming convention? I've not found that in the documentation. companion object { //1 val MY_CONST = "something" //2 ...
Jodimoro's user avatar
  • 4,575
377 votes
38 answers
548k views

Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15

In Stripe, my client wants email and cardholder name, but the Stripe payment UI doesn't provide that option in com.stripe.android.view.CardMultilineWidget. I wanted to give it a try with the latest ...
Karthy Sbk's user avatar
  • 3,893
377 votes
2 answers
172k views

Sort collection by multiple fields in Kotlin [duplicate]

Let's say I have a list of People which I need to sort by Age first and then by Name. Coming from a C#-background, I can easily achieve this in said language by using LINQ: var list=new List<...
Fire095's user avatar
  • 3,855
372 votes
20 answers
186k views

What do I use now that Handler() is deprecated?

How do I fix the deprecation warning in this code? Alternatively, are there any other options for doing this? Handler().postDelayed({ context?.let { //code } }, 3000)
Bolt UIX's user avatar
  • 6,822
365 votes
15 answers
244k views

Extend data class in Kotlin

Data classes seem to be the replacement to the old-fashioned POJOs in Java. It is quite expectable that these classes would allow for inheritance, but I can see no convenient way to extend a data ...
Dmitry's user avatar
  • 4,392
360 votes
4 answers
156k views

Difference between List and Array types in Kotlin

What is the difference between List and Array types? It seems can make same operations with them (loops, filter expression, etc..), is there any difference in behavior or usage? val names1 = listOf("...
Daniel Hári's user avatar
  • 7,594
353 votes
35 answers
602k views

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I am trying to consume an API using Retrofit and Jackson to deserialize. I am getting the onFailure error No Creators, like default construct, exist): cannot deserialize from Object value (no delegate-...
José Nobre's user avatar
  • 4,797
351 votes
11 answers
259k views

Kotlin: how to pass a function as parameter to another?

Given function foo : fun foo(m: String, bar: (m: String) -> Unit) { bar(m) } We can do: foo("a message", { println("this is a message: $it") } ) //or foo("a message") { println("this is a ...
mhshams's user avatar
  • 16.7k
347 votes
33 answers
1.1m views

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

I've got a gradle FAILURE: ..."Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0." Case description: Attached to the project codebase the next libs: APP/...
Philipp Buhaievskiy's user avatar
341 votes
10 answers
150k views

Default interface methods are only supported starting with Android 7.0 (Nougat)

I upgraded to Android Studio 3.1 and I'm getting the following error: Default interface methods are only supported starting with Android N (--min-api 24): void android.arch.lifecycle....
j2emanue's user avatar
  • 62k
339 votes
9 answers
225k views

How to make primary key as autoincrement for Room Persistence lib

I am creating an Entity (Room Persistence Library) class Food, where I want to make foodId as autoincrement. @Entity class Food(var foodName: String, var foodDesc: String, var protein: Double, var ...
Sachin Chandil's user avatar
337 votes
7 answers
175k views

What is the Kotlin double-bang (!!) operator?

I'm converting Java to Kotlin with Android Studio. I get double bang after the instance variable. What is the double bang and more importantly where is this documented? mMap!!.addMarker(MarkerOptions(...
mbr_at_ml's user avatar
  • 3,725
321 votes
6 answers
53k views

Kotlin and new ActivityTestRule : The @Rule must be public

I'm trying to make UI test for my android app in Kotlin. Since the new system using ActivityTestRule, I can't make it work: it compiles correctly, and at runtime, I get: java.lang.Exception: The @...
Geob-o-matic's user avatar
  • 6,039
319 votes
10 answers
320k views

Kotlin – String formatting

Kotlin has an excellent feature called string templates. val i = 10 val s = "i = $i" // evaluates to "i = 10" But is it possible to have any formatting in the templates? For ...
Dmitry Romanov's user avatar
318 votes
25 answers
284k views

How can I get a random number in Kotlin?

A generic method that can return a random integer between 2 parameters like ruby does with rand(0..n). Any suggestion?
Yago Azedias's user avatar
  • 4,778
311 votes
12 answers
250k views

`break` and `continue` in `forEach` in Kotlin

Kotlin has very nice iterating functions, like forEach or repeat, but I am not able to make the break and continue operators work with them (both local and non-local): repeat(5) { break } (1..5)....
voddan's user avatar
  • 33.2k
309 votes
10 answers
243k views

What does the suspend function mean in a Kotlin Coroutine?

I'm reading Kotlin Coroutine and know that it is based on suspend function. But what does suspend mean? Can Coroutine or function get suspended? From https://kotlinlang.org/docs/reference/coroutines....
onmyway133's user avatar
  • 47.3k
308 votes
27 answers
277k views

How to set compileJava' task ( 11) and 'compileKotlin' task (1.8) jvm target compatibility to the same Java version in build.gradle.kts?

Build.gradle.kts buildscript { repositories { google() mavenCentral() gradlePluginPortal() } dependencies { classpath ("com.android.tools.build:gradle:...
jitendra kumar's user avatar
306 votes
9 answers
105k views

Warning "Kotlin plugin version is not the same as library version" (but it is!)

I have an Android studio project in which I have added a Java library module, which I call core. My three Gradle build files look like this. project/build.gradle buildscript { ext.kotlin_version ...
Leo Aso's user avatar
  • 12.3k
300 votes
14 answers
391k views

Android Get Current timestamp?

I want to get the current timestamp like that : 1320917972 int time = (int) (System.currentTimeMillis()); Timestamp tsTemp = new Timestamp(time); String ts = tsTemp.toString();
Rjaibi Mejdi's user avatar
  • 6,870
296 votes
8 answers
217k views

How to create empty constructor for data class in Kotlin Android

I have 10+ variables declared in Kotlin data class, and I would like to create an empty constructor for it like how we typically do in Java. Data class: data class Activity( var updated_on: String,...
Sai's user avatar
  • 15.6k
292 votes
1 answer
121k views

Convert Kotlin Array to Java varargs

How can I convert my Kotlin Array to a varargs Java String[]? val angularRoutings = arrayOf<String>("/language", "/home") // this doesn't work web.ignoring().antMatchers(...
robie2011's user avatar
  • 3,818
289 votes
2 answers
483k views

How can I generate random number in specific range in Android? [duplicate]

I want to generate random number in a specific range. (Ex. Range Between 65 to 80) I try as per below code, but it is not very use full. It also returns the value greater then max. value(greater then ...
Mohit Kanada's user avatar
  • 15.7k
285 votes
15 answers
342k views

How to call a function after delay in Kotlin?

As the title, is there any way to call a function after delay (1 second for example) in Kotlin?
Nguyen  Minh Binh's user avatar
284 votes
5 answers
88k views

What does 'by' keyword do in Kotlin?

While developing for android I sometimes come across something that looks like this: var someModel: someViewModel by notNullAndObservable { vm -> ... } I don't understand what the significance ...
Mark's user avatar
  • 10.6k
283 votes
15 answers
201k views

Setting text in EditText Kotlin

I am trying to set text in a EditText but it says: Type mismatch. Required: Editable Found: String My code is as follow: String name = "Paramjeet" val nametxt = findViewById (R.id.nametxt) as ...
Paramjeet Singh's user avatar
281 votes
8 answers
87k views

What is the difference between launch/join and async/await in Kotlin coroutines

In the kotlinx.coroutines library you can start new coroutine using either launch (with join) or async (with await). What is the difference between them?
Roman  Elizarov's user avatar
271 votes
44 answers
513k views

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details build:gradle(Module:app) buildscript { repositories { maven { url '...
Ankur_009's user avatar
  • 3,600
269 votes
13 answers
162k views

startForeground fail after upgrade to Android 8.1

After upgrading my phone to 8.1 Developer Preview my background service no longer starts up properly. In my long-running service I've implemented a startForeground method to start the ongoing ...
Rawa's user avatar
  • 13.7k
269 votes
9 answers
65k views

NullPointerException when trying to access views in a Kotlin fragment

How to use Kotlin Android Extensions with Fragments? If I use them inside onCreateView(), I get this NullPointerException exception: Caused by: java.lang.NullPointerException: Attempt to invoke ...
solidak's user avatar
  • 5,063

1
2 3 4 5
1927