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.
kotlin
96,331
questions
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?
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 ...
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 ...
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 { ...
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.
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 ...
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?
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?
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?
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 ...
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 ...
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 ...
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 ...
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 ...
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?
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> = ...
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 ...
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?
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, ...
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 ...
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
...
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 ...
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<...
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)
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 ...
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("...
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-...
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 ...
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/...
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....
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 ...
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(...
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 @...
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 ...
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?
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)....
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....
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:...
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 ...
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();
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,...
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(...
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 ...
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?
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 ...
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 ...
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?
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 '...
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 ...
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 ...