Skip to main content

Posts

Renaming types on Import

The following snippet of code illustrates how the rename functionality works in Kotlin after importing a type. import kotlin.random.Random as KRandom import java.util.Random as JRandom fun useDifferentRandomClasses(): String {     return "Kotlin random: " +             KRandom.nextInt( 2 ) +             " Java random:" +             JRandom().nextInt( 2 ) +             "." } In the above snippet of code, we see that we are importing two Random types. We are able to use KRandom for the type imported from Kotlin and JRandom for the type imported from java.util.Random

varargs and array destructuring in Kotlin

Introduction The following post illustrates the use of varargs (variable number of arguments) and array destructing feature in Kotlin langauge. varargs This feature allows multiple arguments of a same type to be passed to a method and not using a collection like Array or list. This feature in java is implemented using the 3 consecutive dots notation given below ... Java Example public String getByValues (String... values) { // ... } Array destructuring With array destructuring, we can be able to use the elements of the array without looping through or pulling out by index which needs careful access as we might get array out of bounds exceptions if not checked. Sample Code fun main() {     val c1 = Color( "red" )     val c2 = Color( "Blue" )     val c3 = Color( "Green" )     val colors = arrayOf(c1, c2, c3)     val manyColors = arrayOf(*colors, c2.copy())     printColors(c1, c2, c3, message = "The color is: " ) // variable number of arg

Kotlin Data Classes and Smart Casts

Introduction Kotlin is a language that is built by the Jetbrains team and opensource contributors. The following are the goals that this language helps us achieve (not full set, for more details please visit kotlinlang.org Modern, concise and safe programming language A productive way to write server‑side applications (still using the frameworks that target JVM) Cross-platform layer for native applications Big, friendly and helpful community Kotlin Data Classes Below I am giving some of the kotlin snippets and short descriptions on what they can perform. Keep in mind that kotlin achieves very concise code data class Person ( val name: String , val age: Int ){     } fun getPeople(): List <Person> {     return listOf(Person( "Alice" , 29 ), Person( "Bob" , 31 )) } fun comparePeople(): Boolean {     val p1 = Person( "Alice" , 29 )     val p2 = Person( "Alice" , 29 )     return p1 == p2   // should be true } In the snippet above, we

The Key from Stackoverflow

Introduction For many years, we have been dealing with memes like try{ doSomething(); }catch(Exception ex) { println(getSolutionFromStackoverflow(ex)) }finally { testAndApplyThefix() } fun getSolutionFromStackoverflow(val ex:Exception) { curl get stackoverflow.com?q=ex.message ... } where the developers run into an error, they immediately lookup the exception in stackoverflow.com and get the solution and validate and close the error. This is a real one that is available from drop.com The original stackoverflow blogpost is here:  https://stackoverflow.blog/2021/09/28/become-a-better-coder-with-this-one-weird-click/ Looks like these will be part of a developer toolset in the near future

understanding the difference between var and let in javascript

Introduction Javascript has multiple ways of declaring variables in the code as given below. However each type of usage has its own context. let x = 10; const y =10; var z = 10 Problem Statement I recently came across a problem statement regarding the above type of variable declaration and usage Snippet: 1 In the below snippet, the output will be 3,3,3. The reason for this behavior is that in javascript, the variable defined as var will be referring to the address of i since it has a function scope so, whenever the value of i is incremented, the change will be reflected inside the setTimeout method as well as they are pointing to the same address for ( var i = 0 ; i < 3 ; i++) { setTimeout ( () => console . log (i), 1 ); } Snippet2 for ( let i = 0 ; i < 3 ; i++) { setTimeout ( () => console . log (i), 1 ); } In the above snippet, we have used a variable with let keyword which has a block scope, so there is a copy of i inside the setTimeout. Hence the above snippet

Extract value of property in a json objects collection

Introduction  [Looking for a needle in haystack] When we have a huge chunk of JSON object or collection of JSON objects and have to get the value of a specific property form the JSON, we will need a tool to get us the value extracted or manually use any editor and search for the key and look up its values.  This is a very tedious job and takes more effort for a person to get this job done Problem Statement  In case of searching for a needle in the haystack, we might have search functionality, however to extract out the values, we must use some sort of regex or other complex mechanism to get the value Solution  In order to overcome the above problem, I have created a simple application using HTML and Javascript that can get this job done very fast. Basic understanding of how objects and keys work will be sufficient to get the job done and I am not building something super special, however, we need a tool that can be handy than write a code each time and attempt to fix the errors or make

Preventing iFrame injection in a .net MVC web app

The Problem Statement There is an issue that an malicious attacker can inject iframes within the app so that the iframe can have a source to an external application that is outside of the parent app's domain. Sample Lets consider the app to be hosted at https://app.com/. The attacker could inject an iframe that will contain a source to https://malicious.com/ In this case, we have to prevent any iFrames injected in our app that can point to a domain that is different from ours. To fix this issue, add the following header in the response for each request Solution X-Frame-Options : SAMEORIGIN Web.config Solution <system.webServer> <httpProtocol> <customHeaders> <add name="X-Frame-Options" value="SAMEORIGIN" /> </customHeaders> </httpProtocol> </system.webServer> Global.asax solution protected void Application_Start () { AntiForgeryConfig . SuppressXFrameOptionsHeader = true ; }

Safe way to converting array of strings as Integers in javascript

The Problem This is a very short post on how to be very careful when converting a collection (array) of strings to integers Let us assume that we receive from an API call or from some other source a collection of numbers in string format Example ["1","9","2"] In this case we might be planning to use the map function along with the parseInt to get the job done as given below ["1","9","2"].map(parseInt) However, the catch here is that the above method will return the below response (3) [1, NaN, NaN] This will be a lot confusing to many because the first number gets parsed and the remaining ones does not. Let us consider another example ["10","10","10","10"].map(parseInt) This results in a similar output where the developer might get even puzzled [10, NaN, 2, 3] This looks like the last 2 numbers are getting printed like their i