Category : Kotlin Interview Q&A

In this article you will examine various techniques to find out whether a string is numeric or not in Kotlin. Method 1: Check if a string is numeric or not using regular expressions (regex) fun main(args: Array<String>) { val string = “-1234.15” var numeric = true numeric = string.matches(“-?\\d+(\\.\\d+)?”.toRegex()) if (numeric) println(“$string is a number”) ..

Read more

In this article you will learn today how to sort an array list of custom objects by the property given in Kotlin. Sort ArrayList of Custom Objects By Property import java.util.* fun main(args: Array<String>) { val list = ArrayList<CustomObject>() list.add(CustomObject(“Z”)) list.add(CustomObject(“A”)) list.add(CustomObject(“B”)) list.add(CustomObject(“X”)) list.add(CustomObject(“Aa”)) var sortedList = list.sortedWith(compareBy({ it.customProperty })) for (obj in sortedList) { ..

Read more

In this article you will learn today how to sort a given map in Kotlin. Sort a map by values fun main(args: Array<String>) { var capitals = hashMapOf<String, String>() capitals.put(“Nepal”, “Kathmandu”) capitals.put(“India”, “New Delhi”) capitals.put(“United States”, “Washington”) capitals.put(“England”, “London”) capitals.put(“Australia”, “Canberra”) val result = capitals.toList().sortedBy { (_, value) -> value}.toMap() for (entry in result) { ..

Read more

In this article you will learn today how to convert string values to enum using the valueOf () method of an enum in Komalin. Lookup enum by string value enum class TextStyle { BOLD, ITALICS, UNDERLINE, STRIKETHROUGH } fun main(args: Array<String>) { val style = “Bold” val textStyle = TextStyle.valueOf(style.toUpperCase()) println(textStyle) } R..

Read more

In this article you will learn today how to convert output to string using string initializer in Kotlin. Convert OutputStream to String import java.io.* fun main(args: Array<String>) { val stream = ByteArrayOutputStream() val line = “Hello there!” stream.write(line.toByteArray()) val finalString = String(stream.toByteArray()) println(finalString) } Result Hello the..

Read more

In today’s article you will learn how to convert inputstream to string in Kotlin program? Convert InputStream to String import java.io.* fun main(args: Array<String>) { val stream = ByteArrayInputStream(“Hello there!”.toByteArray()) val sb = StringBuilder() var line: String? val br = BufferedReader(InputStreamReader(stream)) line = br.readLine() while (line != null) { sb.append(line) line = br.readLine() } br.close() ..

Read more

Today we will read on this page how to convert stack trace into string in Kotlin. Convert stack trace to a string import java.io.PrintWriter import java.io.StringWriter fun main(args: Array<String>) { try { val division = 0 / 0 } catch (e: ArithmeticException) { val sw = StringWriter() e.printStackTrace(PrintWriter(sw)) val exceptionAsString = sw.toString() println(exceptionAsString) } } ..

Read more