Qualified it in kotlin

As the docs say at https://kotlinlang.org/docs/reference/this-expressions.html#qualified, one can use qualified this to specify an outer context to use. Is there any way of doing this with it? IntelliJ keeps saying that there is a sytax error.

Kotlin .let {} null safety presumably false error

When using the .let { } function I noticed that when doing the following: bucket?.assignedVariantName.let { bucket?.determineVariant() <-- guarantee safety for bucket } You have to guarantee safety for bucket in this case i.e. bucket?. or bucket!! while null safety is already guaranteed by using ?.let then I noticed when doing the following: bucket?.assignedVariantName?.let { <-- added safety check for property bucket.determineVariant() <-- doesn't need to guaran

Why am I getting an ArrayIndexOutOfBoundsException running this particular Cucumber step in Kotlin?

I'm running with a Cucumber JVM feature file, using Java8 and PicoContainer. I've stripped these steps right down so they're empty, and I'm still getting an error. Here's my feature: Feature: Full Journey Scenario: Can load a typical JIRA csv and calculate the distribution from it Given a typical JIRA export "/closed_only_JIRA.csv" When I import it into Montecarluni Then I should see the distribution """ 6, 15, 3, 14, 2, 5, 6, 8, 5, 10, 15, 4, 2, 1 """ When I copy it to the clipboard Then I s

How to setup Kotlin on Android Studio?

I have some troubles with the settings in Android Studio with Kotlin plugin? Someone can help me? I follow the documentation guide on the official page https://kotlinlang.org/ , but have not effect.

Kotlin quadruple, quintuple, etc. for destructuring

I am looking for a clean way to create destructurable objects in-line. kotlin.Pair and kotlin.Triple cover a lot of use cases, but sometimes there are more objects that are needed to be passed. One sample use case is RX's zip function, where the results of several I/O calls need to be mapped into another object: Single .zip(repositoryA.loadData(someId), repositoryB.loadData(someId), repositoryC.loadAll(), repositoryD.loadAll()), { objectA, objectB, objec

Kotlin Is "org.jetbrains.anko:anko-commons:$anko_version" wrong?

The following Code 1 is from webpage http://www.tellmehow.co/kotlin-anko-coroutines/ Code 1 dependencies { compile "org.jetbrains.anko:anko-commons:$anko_version" } It seems that the Code 1 is wrong, it should be Code 2, right? Code 2 dependencies { compile "org.jetbrains.anko:anko-common:$anko_version" }

how to fetch information using volley library in kotlin

I've a php file on a server, and I have to fetch the information but i don't know how to pass a parameter to the query. For example, if I have this query: SELECT * FROM accounttable WHERE idaccount = 1, i want to pass this 1 as a parameter, how can i do? val stringRequest = StringRequest(Request.Method.POST, URL, Response.Listener<String>{ s -> try { val array = JSONArray(s) for (i in 0..array.length() - 1) { val objectAcc

Kotlin Explanation as to why this String comparison results in false?

Could anyone explain why the following line of code results in false. The code returns true if the Strings aren't capitalized. Shouldn't ignoring the case mean the result is the same? System.out.print( String("Carthorse".toCharArray().sortedArray()) .equals(String("Orchestra".toCharArray().sortedArray()),true) )

Kotlin - get T::class.java from class generic type parameter

I'm trying to build a generic repository around Corda's vault. It should look something like this: class VaultRepository<out T : ContractState>(private val services: CordaRPCOps) { fun getUnconsumedStateByExternalId(externalId: String): T { return services.vaultQuery<T>(...).states.single().state.data } } But I get this error: Cannot use 'T' as reified type parameter I could use another vaultQuery function, which takes a Class<T> instead as a parameter

Kotlin Cast types to their respective not nullable types

I have an extension function something like this: inline fun <A, B, C> Pair<A, B>.notNull(code: (A, B) -> C) { if (this.first != null && this.second != null) { code(this.first, this.second) } } with that, I can do something like this: Pair(username, password).notNull { user, pass -> // code to execute when username and password is not null } The problem is, user and password type is still in nullable form, so I still need to use ?. to call us

Kotlin Spring WebFlux Webclient receiving an application/octet-stream file as a Mono

I'm prototyping a small Spring WebFlux application in Kotlin. This application needs to GET a tar archive from a remote REST endpoint and store it locally on disk. Sounds simple. I first created an integration test that starts the spring server and one other WebFlux server with a mock REST endpoint that serves the tar archive. The test should go like: 1) app: GET mock-server/archive 2) mock-server: response with status 200 and tar archive in body as type attachment 3) app: block until all b

Kotlin apache storm: how to transform (make a new) tuple

This is probably not the best practice in storm but we are working with a library that requires us to transform the values of a tuple in our bolt to filter out only objects of a certain class. I know how to do the filter, however, I'm not sure how I can put together a new tuple with the transformed (i.e., filtered) tuple: override fun execute(input: Tuple?) { val filteredValues = input.values.filterIsInstance(MyClass::class.java) // ? how do I make a new tuple with filteredValues val newT

Is there not an idiomatic way to have a (secondary) constructor that derives values for the primary constructor in Kotlin?

I have a simple Kotlin class: data class ValveSpan(val begin:Duration, val end:Duration, val key:String):Comparable<ValveSpan> { ... } Because it's a data class, I must have a primary constructor with one or more values in it. And that's fine, I like the terse expression of it. But when I want to make a secondary constructor that populates one from doc like object (similar to JSON), it gets weird: constructor(doc:TSON):this(doc["begin"].duration!!, doc["end"].duration!!, doc["val

Multi-platform InputStream Alternative in Kotlin?

I’m looking for a multi-platform alternative to input streams. My concrete task is to fetch an encrypted file from a remote server via https and decrypt it on demand. In Java land I would an implement InputStream which proxies the reads to the input stream from the https library. How can I do the same in kotlin targeting multiple platforms. I see ktor returns an ByteReadChannel, but I don’t know which functions. I’m lost and don’t know where to start. Thanks for your help in advance.

Override getters in Kotlin?

So I have an abstract class Composition, which has two children: one is a Track, and one is an Album (which is a group of Tracks). class Composition(val name: String, ...) class Track(name: String): Composition(name) class Album(name: String, val tracks: List<Track>): Composition(name) So far, so good. Now, I have the duration that is added. It is abstract in Composition, so I can override it in the children: abstract class Composition(...){ abstract fun getDuration(): Int } Now,

Kotlin MutableLiveData: Cannot invoke setValue on a background thread from Coroutine

I'm trying to trigger an update on LiveData from a coroutine: object AddressList: MutableLiveData<List<Address>>() fun getAddressesLiveData(): LiveData<List<Address>> { AddressList.value = listOf() GlobalScope.launch { AddressList.value = getAddressList() } return AddressList } but I get the following error: IllegalStateException: Cannot invoke setValue on a background thread Is there a way to make it work with coroutines?

How to calculate a cubic root in Kotlin?

in kotlin there is an internal math library and I only find the square root but there is no cubic root. import kotlin.math.sqrt import kotlin.math.pow fun Formule(a:Int):Double{ //no working //rs = a.pow(1/3) //function retun rs } fun main(args: Array<String>){ val calc = Formule(9) }

Kotlin Process Images and resize them on a Ktor server

I am trying to receive an image using a Ktor server, and process it, all the Android libraries aren't working as they use things like BitmapFactory, java.awt.* , Buffered images and etc. Does Ktor have any set of tools to process images? What I am trying to achieve is to receive an image and resize it.

Why Kotlin allow write main function with no arguments?

Recently, I started to learn Kotlin and figured out that the main() function may be written without arguments like this: fun main() { dayOfWeek() } How is this possible and what Kotlin is doing under the hood? Java doesn't allow us to do so.

What is receiver in Kotlin?

someone to tell me what is the receiver in Kotlin? I checked the official documentation but I can't understand what it is. Also you could tell me what function Int. has in the following code: Int.(Int, Float) -> Int

Kotlin object, an implementation vs instance

In Objects in Kotlin: Create safe singletons in one line of code (KAD 27) Antonio Leiva states: In fact, an object is just a data type with a single implementation. I would expect to see the term instance rather than implementation used here. Is there some nuance that I am missing?

Kotlin null value in init block of parent class

I was creating a very simple kotlin program and saw a weird behavior for parent class. The code is: fun makeSalt(name:String) = Spice(name, "non-spicy") fun main(args: Array<String>) { var salt : Spice = Spice("salt", "non-spicy") println("Salt heat = ${salt.heat}") val spicelist = listOf<Spice>( Spice("salt", "non-spicy"), Spice("turmeric", "mild"), Spice("Pepper", "hot"), Spice("Chilli", "hot"), Spice("Sugar", "non-spicy")

Kotlin Async doesn't appear to run concurrently

The following code uses 2 async function calls: import kotlinx.coroutines.* import kotlin.system.* fun main() = runBlocking<Unit> { val time = measureTimeMillis { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } println("The answer is ${one.await() + two.await()}") } println("Completed in $time ms") } suspend fun doSomethingUsefulOne(): Int { delay(3000L) // pretend we are doing something useful here p

Kotlin coroutines Mutex owner usage

What is the expected usage of owner in a kotlinx.coroutines.sync.Mutex? From what I understand a Mutex.withLock will make any calling coroutine after the first (witch locked the mutex), await until it is unlocked, and then hold the lock themselves. So, what could be causing the following error? 2019-12-06 15:29:30.508 6380-6840/com.[...] E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-3 Process: com.[...], PID: 6380 java.lang.IllegalStateException: Already locked by [...].

Kotlin Apache Camel Response Type Mismatch for Multiple Apache Camel REST Services

I am testing out a contrived REST API using the Apache Camel REST DSL. I am attempting to POST to the /login route shown below and getting an unexpected response. Here is my REST configuration and REST services. restConfiguration().apply { component = "undertow" port = "8082" bindingMode = RestBindingMode.json dataFormatProperty("prettyPrint", "true") apiContextPath = "api-doc" apiProperty("api.title", "Online Bookstore API") apiProp

Kotlin When is it appropriate to use @Singleton and @Prototype in Micronauts?

I read so many bad things about singleton pattern (What is so bad about singletons?), however, @Singleton is used everywhere in this Micronaut doc to illustrate inversion of control https://docs.micronaut.io/1.3.0.M2/guide/index.html#ioc When is it appropriate to use @Singleton? For example, if I have a UserInfoService that has getUserInfo, createUserInfo, updateUserInfo method, is it a good idea to use @Singleton? Another separate question is when do I use @Prototype, because if I don't use

How to pass-by-value in Kotlin?

I'm doing a programming contest with Kotlin, and there are lots of times when I need parameter is pass-by-value, how do I do that? fun main() { val p = Person(18) println(p.age) // 18 changeAge(p) println(p.age) // 21, but I want it still 18 } data class Person(var age: Int) fun changeAge(p: Person) { p.age = 21 }

Make na abstraction to kafka consumer using ktor and kotlin

I'm creating a abstraction for consumer and producer Kafka, to avoid duplicate code all the time. So i created a lib using kotlin and gradle, named "kafka-commons", and put the following code: For Kafka producer: fun producer( bootstrapServers: String, idempotence: Boolean, acks: Acks, retries: Int, requestPerConnection: Int, compression: Compression, linger: Int, batchSize: BatchSize ): KafkaProducer<String, Any> { val prop: HashMap<String, Any>

How to establish getter & setter for secondary constructor in data class for kotlin?

I need a data class with two different constructors as shown. But how do I do getter & setter for the secondary constructor of data class in Kotlin? I tried multiple changes, not able to figure it out. In the below snippet, I am not getting the right import for get() and set() data class user(var phone: String) { constructor(phone: String, name : String) : this(phone) { var name: String = name get()= field set(value) { field = value } }

Why can't I parallel operation when I use either delay() or yield() in Kotlin?

The Code A, Code B and Code C get the same result Result All. I think the Code B or Code C should get the result Result MyThink because I have added either delay() or yield(). It seems that flow.collect {...} is a block function. Code A fun foo(): Flow<Int> = flow { println("Flow started") for (i in 1..3) { delay(500) emit(i) } } fun main() = runBlocking<Unit> { println("Calling foo...") val flow = foo() println("Calling collect...")

Gradle 6+ : compile groovy before kotlin

I'm working on a project combining groovy and kotlin. My Kotlin classes require objects from groovy part, how can i make gradle compile groovy before kotlin ? I'm using Gradle 6.3 with kotlin-dsl I've tried several solutions : srcsets order, tasks order, ... Nothing seems to work Any idea ?

Kotlin What functional method would help me to implement a speedback algorithm?

Speedback is the merging of speed-dating with feedback: a 2 min. 1-on-1 talk with all members of a group of people. I've made a similar question in Computer Science to get some clues about the algorithm, but it's hard to convert it to functional programming. Consider the input: val team = setOf("alexandre", "sergiu", "joana", "tiago", "susana", "david") I'd like to do like a round robin where all team members have to give feedback to eachother. I want to group people in a way that maximizes

Only get interface fields of kotlin-object

I want to reduce an object down to its basic fields (comming from an interface): override fun findBasicById(deliveryAddressId: Long): BasicDeliveryAddress? { val basicDeliveryAddress = findById(deliveryAddressId) as BasicDeliveryAddress? // returns a DeliveryAddress object return basicDeliveryAddress // Here I still get the full DeliveryAddress! } However, basicDeliveryAddress still contains all fields from the class which implements the interface. How can I get rid of all fields, not

Get a property of task? in Gradle kotlin

I'm trying to convert my build.gradle file to build.gradle.kts. I almost do that but only one problem left. I don't have any idea how to convert code below. Kotlin import org.asciidoctor.gradle.AsciidoctorTask ... apply(plugin = "org.asciidoctor.convert") val snippetsDir = file("build/generated-snippets") tasks.named<AsciidoctorTask>("asciidoctor") { attributes( mapOf( "snippets" to snippetsDir ) ) inputs.d

Kotlin How to execute multiple codes in a when block when their conditions is true?

I'm aware that when { } can be used as a replacement to if-else branches. However, is it possible to execute multiple branches if the conditions are true? Example: val x = 5 val y = 4 when { x.isOdd() -> print("x is odd") //True, prints "x is odd" y.isEven() -> print("y is even") //Also True, but doesn't get executed else -> print("x+y is even.") } Is there any way so the second line is also executed?

Kotlin How to rewrite a chain of else if using when

So I am trying to use when in Kotlin, instead of the chain of else if statements that I have. companion object { private fun min(a: Date?, b: Date?): Date? { return if (a == null) b else if (b == null) a else if (a.before(b)) a else b I want my return type to use when and not the else if

Kotlin androidMain and android tests folder not recognised as module

I’ve been struggling with this issue since days but can’t find any solution so I hope I can get any help here. I created a Multiplatform project with Mobile Application template from IntelliJ IDEA 2020.2.1 and since project setup androidMain and AndroidTest folders are not recognised as module. This seems not to be a problem when launching androidApp task or PackForXcode as references to expect/actual definitions are resolved but idea suggestions shows anyway how androidMain reference seems to b

Kotlin - Extract value from function

I'm working about a Kotlin code and I need to use a value that is create inside a function. I share my code: val Myspinner: Spinner = findViewById(R.id.spinner) if (Myspinner!= null) { val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, pulsatil) Myspinner.adapter = adapter } Myspinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{ //val pulsatil2 = Myspinner.selectedIte

Kotlin How to add additional collection data to document with Cloud Firestore?

Data is read from cloud firestore (red) which is static data and stored locally in a room database private val _fetchedJourneys = MutableLiveData<List<Journey>>() override val fetchedJourneys: LiveData<List<Journey>> get() = _fetchedJourneys override suspend fun getJourneys() { FirebaseFirestore.getInstance() .collection(COLLECTION_JOURNEY) .get() .addOnCompleteListener { task -> if (t

How to solver error for kotlin coroutines flow?

I tried to use NetworkBoundResource for my MVVM Model and after i follow some tutorial, i'm having an error look this 10-21 14:15:04.073 31376-31376/com.example.mvvmsecondmodel E/Process: android_os_Process_getProcessNameByPid pid is 31376 10-21 14:15:04.074 31376-31376/com.example.mvvmsecondmodel E/Process: android_os_Process_getProcessNameByPid value is mvvmsecondmodel 10-21 14:15:04.416 31376-31421/com.example.mvvmsecondmodel E/SQLiteLog: (283) recovered 8 frames from WAL file /data/data/com.

Correct way to implement withContext but without introducing a CoroutineScope/Job in Kotlin

Is the below implementation of withContext to call the block with extended coroutineContext valid? suspend fun <T, R> withContext(context: CoroutineContext, receiver: T, block: suspend T.() -> R): R { val newCoroutineContext = coroutineContext + context return suspendCoroutine { cont -> block.startCoroutine(receiver, Continuation(newCoroutineContext) { cont.resumeWith(it) }) } } Kind of similar to withContext from kotlinx.coroutines but at a lower level without J

what's different data and dataa property in kotlin?

what's different between the two? fun main(){ class A<T>(name : T){ val dataa : T = name // <-- no problem using private modifier or not fun getData() : T = dataa } class B<T>(name : T){ val data : T = name //^^^ i get the error and i have to use private modifier or use the @JvmField fun getData() : T = data } } what is the difference between val data and val dataa ? is data the default property in kotlin ?

Kotlin How to get first element from a Room DB flow?

I have a function like so in my Repository fun getSelfReportMetaById(cardId: String): Flow<SelfReportMeta?> { return selfReportMetaDao.getById(cardId) .map { it.map { entity -> entity.toSelfReportMeta() } } .map { it.firstOrNull() } } The idea is to get a unique field out of my database. I do not expect multiple elements per cardId. In my viewModel, I want to check the DB to see if the key already exists. I

Kotlin How to split operators and operands into two arrays?

I want to split this content into two seperate arrays numbers and operators in Kotlin. The content is "2*5-6+7". This is my code which doesnt work: val arrnum = content.split("[-+*/]").toTypedArray() val operator = content.split("[0123456789]").toTypedArray()

Kotlin Camel Quarkus does not seem to be using the Quarkus objectmapper

I have a Camel ReST route that uses Jackson to convert a collection to JSON but it's throwing an error when the object in the collection includes a LocalDate (everything works fine without LocalDates). com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type java.time.LocalDate not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" I have added a class to customise the Quarkus ObjectMapper: @Singleton class MyO

Kotlin Inequality within "when" statement outputs error

Here I have a program which assigns the value of a variable based on different conditions: fun main(args: Array<String>) { var age = readLine()!!.toInt() var string_age = when(age) { in 0..11 -> "Child" in 12..17 -> "Teen" in 18..64 -> "Adult" age > 64 -> "Senior" else -> "Invalid age" } print(string_age) } However, the inequality "age > 64" returns "incompa

Kotlin Realtime database not stored data

l cant save data Firebase realtime database no error code. auth create user but database not stored user data inside app. l change database rules { "rules": { ".read": true, ".write": true } } l close firewall , try to test another app,I deleted the application completely from firebase and re-created it and downloaded the google-services.json file again. but can't solve problem.I tried a lot of different code structures, none of them worked this is my sign

Kotlin How to make "inappropriate blocking method call" appropriate?

I am currently trying to leverage kotlin coroutines more. But I face a problem: when using moshi or okhttp inside these coroutines I get a warning: "inappropriate blocking method call" What is the best way to fix these? I really do not want to be inappropriate ;-)

  1    2   3   4   5   6  ... 下一页 最后一页 共 37 页