Posts

Showing posts with the label kotlin

Using TreeTranslator to rename functions not working for Kotlin

Image
Using TreeTranslator to rename functions not working for Kotlin I am trying to rename a method in a Java interface and a function in a Kotlin interface during building according to AST (Abstract Syntax Tree) rewriting. For this question we ignore the implications that renaming a method/function brings for invocations. To find the method/function to rename I am using a custom annotation and annotation processor. I have it working for the Java interface by following these instructions. I created a new project with three modules. The app module, annotation module and annotation processor module. The app module is an Android App and contains two separate Java and Kotlin interface files with one annotated method/function each. RenameJava.java package nl.peperzaken.renametest; import nl.peperzaken.renameannotation.Rename; public interface RenameJava { @Rename void methodToRename(); } RenameKotlin.kt package nl.peperzaken.renametest import nl.peperzaken.renameannotation.Rename interfa...

Casting Kotlin ArrayLists ClassCastException

Casting Kotlin ArrayLists ClassCastException I have a MutableList<Card> called cards that I am sorting based on one of the properties, using the sortedWith function. This returns a sorted generic list type, so a cast is necessary. However, when I cast the list, it crashes with a ClassCastException: MutableList<Card> cards sortedWith private var cards: MutableList<Card> = ArrayList() ... cards = cards.sortedWith(compareBy{it.face}) as ArrayList<Card> java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList EDIT: I just realized I need to use the more generic type of cards for the cast, MutableList<Card> . Now, can someone explain why the cast with ArrayList fails? MutableList<Card> 2 Answers 2 The cast fails because the list returned by sortedWith function is not an instance of java.util.ArrayList . sortedWith java.util.Arr...

Dagger Lazy during constructor injection

Dagger Lazy during constructor injection I realize that the recommended way of accomplishing Lazy injection with Dagger is to add Lazy to a field injection point. For instance, Lazy Lazy class Foo { @Inject lateinit var bar: Lazy<Bar> fun useBar() = bar.get().doSomething() } What about using constructor injection? I have not seen anyone doing it. class Foo @Inject constructor(private val fizz: Fizz, private val bar: Lazy<Bar>) { fun useBar() = bar.get().doSomething() } To summarize when doing Dagger lazy injection, can I use Lazy<Bar> in a constructor? Or is my only option to move Lazy<Bar> to a field injection while keeping other non-Lazy dependencies in the same class injected via the constructor? Lazy<Bar> Lazy<Bar> Thanks for any pointers! Have you tried? – AutonomousApps Jul 2 at 7:30 ...

How to catch exceptions from spring webflux controller?

How to catch exceptions from spring webflux controller? I am using javax validations in my controller with @Valid @RequestBody . When the server receives invalid data it throws error but I want to handle that error and return custom formatted error. I am unable to catch exception in my controller advice. I am using spring webFlux so can't use the bindingResult. How can I handle that exception? Here is my code @Valid @RequestBody Controller @PostMapping fun createPerson(@Valid @RequestBody resource: PersonResource): Mono<Person> { return personService.save(resource.toPerson()) } Resource data class PersonResource( val id: String?, @field:NotEmpty val name: String, ... } ErrorHandler @ControllerAdvice class ApiErrorHandler { @ExceptionHandler(IllegalArgumentException::class) fun handleValidationErrors(e: IllegalArgumentException): ResponseEntity<*> { // never reaches here } } Maybe this stackoverf...

Adding new element(s) to Spinner Adapter

Adding new element(s) to Spinner Adapter I'm new to Kotlin language and I'm going to load Spinner data from the website. For this reason, I used Fuel Library as my httpGet , httpPost and ... helper library and simply the Spinner Control for showing that data to the user. Below is my tried code: Kotlin Spinner httpGet httpPost Spinner var listOfLesson:List<String> = listOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.ostad_page) val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, listOfLesson) "home/GetAllLessons".httpGet().responseString { request, response, result -> when (result) { is Result.Success -> { val lessonsArray: List<tblLesson> = Gson().fromJson(result.value, Array<tblLesson>::class.java).toList() var index:Int = 0 for (lesson: tblLesso...

Comparable arrays in Kotlin

Comparable arrays in Kotlin Coming from a Swift world I'm trying to figure out how to use comparable functions like min() or max() on an array of objects. In Swift I would use the comparable protocol - min() max() class Car: Comparable { let year: Int static func < (lhs: Car, rhs: Car) -> Bool { return lhs.year < rhs.year } static func == (lhs: Car, rhs: Car) -> Bool { return lhs.year == rhs.year } } But how would you do the same in Kotlin? I've tried this but I'm not sure if it's the right approach, or how I would implement the iterable function - data class Car(val year: Int): Comparable<Car>, Iterable<Car> { override fun compareTo(other: Car) = when { this.year < other.year -> -1 this.year > other.year -> 1 else -> 0 } override fun iterator(): Iterator<Car> { TODO("not implemented") } } So your end g...

Kotlin TextView.text +=

Image
Kotlin TextView.text += i have tried txtCalc.text = "The text" + "0" and it doesn't work idownvotedbecau.se/itsnotworking – cricket_007 Jul 1 at 14:27 You might want to look at android data binding if you want to actually use modifiable view strings – cricket_007 Jul 1 at 14:30 2 Answers 2 If you read the current text in the TextView , you'll get a CharSequence , which you'll have to turn into a string before concatenating anything to it: TextView CharSequence textView.text = textView.text.toString() + "0" Or you can just use the append method of TextView : append Te...

Android Obtain all the children that a Layout has (Including Sub-childs)

Android Obtain all the children that a Layout has (Including Sub-childs) Basically what im trying to do is create a function that has a recursive calling , so i can obtain all the RadioButtons, Buttons, FAB, TextView, and even others SubViews ( LinearLayouts, RelativeLayouts, FrameLayout, ViewGroup ). Right now i can obtain all the Layouts but when i wanna access the subcontent of those subViews those values never return... var contentList = ArrayList<String>() fun ManageView(viewGroup: ViewGroup, action: String, context: Activity){ try { loop@ for (i in 0 until viewGroup.childCount) { var child = viewGroup.getChildAt(i) contentList.add(context.applicationContext.resources.getResourceEntryName(child.id)) when (child) { is ViewGroup->{ ManageView(child,"vacant",context) } is RadioGroup -> { contentList.add(context.applicationCon...

TornadoFX filechooser

TornadoFX filechooser I am looking solution for javafx FileChooser (in Kotlin). I stuck on this, I cannot pass root View, because Window! is expected: FileChooser Window! button("open some file") { setOnAction { val fileChooser = FileChooser(); val file = fileChooser.showOpenDialog(???) ... } } What should I pass in this case? Although Ruckus gave you the correct answer below (use the chooseFile and chooseDirectory functions in TornadoFX), I just wanted to point out that you can access the stage via the primaryStage property. If your View is opened using openModal or openWindow you can access your stage via the modalStage property of the View . Stage inherits from Window . – Edvin Syse Nov 22 '16 at 8:19 ...

Kotlin continuing to else clause after return

Kotlin continuing to else clause after return I am trying to figure out how returns work in Kotlin. Right now I have a function that with two nested for loops. All returns should return for the parent function getValue(), one seems to work as expected, the other one does does not. val myArray = arrayOf( MyObj("String 1", mapOf(Pair(MyEnum.apple, "String 2"))), MyObj("String 2", mapOf(Pair(MyEnum.orange, "String 1"), Pair(MyEnum.apple, "String 3"))), MyObj("String 3", mapOf(Pair(MyEnum.orange, "String 2"))) ) val myObj = myArray[1] fun main(args: Array<String>) { getValue(MyEnum.apple) } fun getValue(myEnum: MyEnum) { myObj.myMap.forEach { (enum, str) -> if (enum == myEnum) { myArray.forEach {obj -> if (obj.name == str) { if (checkStuff(obj)) { println("checkStuff returned true") ...

How to use retryWhen only 3 times then give up

How to use retryWhen only 3 times then give up I want to filter when specific exception occurs during execution of some of the upper chain function and try to retry the whole process only 3 times then if it still failes then give up. I came to something like this: val disposable = someFunction(someParameter, delay, subject) .flatMapCompletable { (parameter1, parameter2) -> anotherFunction(parameter1, parameter2, subject) } .retryWhen { throwable -> throwable.filter { it.cause?.cause is ExampleException1 || it.cause?.cause is ExampleException2 || it.cause is ExampleException3 } } .andThen(someStuff()) .subscribe({ Timber.d("Finished!") }, { Timber.d("Failed!") }) How to do it properly? 2 Answers 2 You may use zipWith with a range to achieve this. zipWith range .retryWhen { erro...