How to convert mile to kilometer using kotlin - kotlin

I am new to kotlin... I have no idea how to convert miles to kilometer
MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val name = findViewById<EditText>(R.id.text1)
val ConvertButton = findViewById<Button>(R.id.btn1)
val displayanswer = findViewById<TextView>(R.id.textView1)
}
}

I don't think that's really a kotlin topic.
It's simply a math problema but here is one way to implement it in kotlin :
Using kotlin extensions you can write a function to convert km to miles and miles to km :
fun Float.toKm() = this * 1.60934
fun Float.toMiles() = this / 1.60934
Now when you will have a float that represent a km you'll be able to invoke .toMiles() and when you'll have a float that represent a miles you'll be able to invoke .toKm().
Here is an example :
val kilometers = 10.0F
val miles = 6.0F
println("km ${kilometers} to miles = ${kilometers.toMiles()}")
println("miles ${miles} to km = ${miles.toKm()}")
If you want to read more about extensions : https://kotlinlang.org/docs/extensions.html#extension-functions

I would suggest you define value classes for your types. You can then add conversion functions and arithmetic operations as well. In this example I have defined the plus operator, but you could build on this to make this more full featured
#JvmInline
value class Kilometer(val value: Float) {
fun toMeters() = Meter(value * 1000f)
operator fun plus(other: Kilometer) = Kilometer(value + other.value)
}
#JvmInline
value class Meter(val value: Float) {
fun toKilometers() = Kilometer(value / 1000f)
fun toMiles() = Mile(value / 1.604f)
}
#JvmInline
value class Mile(val value: Float) {
fun toMeters() = Meter(value * 1.604f)
}
fun useIt() {
val km1 = Kilometer(12f)
val km2 = Kilometer(20f)
val km = km1 + km2
val meters = km.toMeters()
val miles = meters.toMiles()
}

Related

Kotlin: How to use higher order functions with OpenEndRange<LocalDate>

I want to use higher order functions like map for open end ranges.
val from = LocalDate.now().minusDays(10)
val to = LocalDate.now()
(from ..< to).forEach(::println)
I tried to copy an example for ClosedRange<LocalDate> but it does not work.
package de.otto.di.extensions
import java.time.LocalDate
class OpenEndRangeLocalDateIterator(
startDate: LocalDate,
private val endExclusive: LocalDate,
private val stepDays: Long
) : Iterator<LocalDate> {
private var currentDate = startDate
override fun hasNext() = currentDate.plusDays(stepDays) <= endExclusive
override fun next(): LocalDate {
val next = currentDate
currentDate = currentDate.plusDays(stepDays)
return next
}
}
#OptIn(ExperimentalStdlibApi::class)
class OpenEndLocalDateRange(
override val start: LocalDate,
override val endExclusive: LocalDate,
private val stepDays: Long = 1
) : Iterable<LocalDate>, OpenEndRange<LocalDate> {
override fun iterator(): Iterator<LocalDate> =
OpenEndRangeLocalDateIterator(start, endExclusive, stepDays)
infix fun step(days: Long) = OpenEndLocalDateRange(start, endExclusive, days)
}
infix operator fun LocalDate.rangeUntil(to: LocalDate): OpenEndLocalDateRange =
OpenEndLocalDateRange(this, to)
It is implemented for Int so I assume it must be possible somehow. How can I achieve this?
The issue here is that you've defined the operator function to return OpenEndRange<LocalDate> rather than OpenEndedLocalDateRange. If you change the return type of your operator function that should fix the issue.
The reason why it isn't working as is is because OpenEndRange doesn't have the higher order functions defined for it (ClosedRange doesn't have them defined as well). Int has it because the operators return an IntRange which indirectly extends Iterable<Int> via IntProgression and Iterable has these higher order functions defined, so, the only missing piece is failing to return the correct type from your operator function.

Kotlin Sorting a list of objects based on their coordinate( lat and long) using Haversine formula

I want to sort a list based on their latitude and longitude...
Here is my code:
import java.util.*
import com.google.gson.GsonBuilder
import java.io.File
import java.io.InputStream
import java.util.Comparator
data class Property(val Pcode: Int, val Locality: String, val State: String, val Comments: String, val Category: String, val Longitude: Double, val Latitude: Double)
class SortPlaces(currentLatitude: Double, currentLongitude: Double) : Comparator<Property> {
var currentLat: Double
var currentLng: Double
override fun compare(property1: Property, property2: Property): Int {
val lat1: Double = property1.Latitude
val lon1: Double = property1.Longitude
val lat2: Double = property2.Latitude
val lon2: Double = property2.Longitude
val distanceToPlace1 = distance(currentLat, currentLng, lat1, lon1)
val distanceToPlace2 = distance(currentLat, currentLng, lat2, lon2)
return (distanceToPlace1 - distanceToPlace2).toInt()
}
fun distance(fromLat: Double, fromLon: Double, toLat: Double, toLon: Double): Double {
val radius = 6378137.0 // approximate Earth radius, *in meters*
val deltaLat = toLat - fromLat
val deltaLon = toLon - fromLon
val angle = 2 * Math.asin(
Math.sqrt(
Math.pow(Math.sin(deltaLat / 2), 2.0) +
Math.cos(fromLat) * Math.cos(toLat) *
Math.pow(Math.sin(deltaLon / 2), 2.0)
)
)
return radius * angle
}
init {
currentLat = currentLatitude
currentLng = currentLongitude
}
}
fun main(args: Array<String>) {
val command = Scanner(System.`in`)
val running = true
while (running) {
val inputStream: InputStream = File("./src/main/kotlin/suburbs.json").inputStream()
val inputString = inputStream.bufferedReader().use { it.readText() }
val gson = GsonBuilder().create()
val packagesArray = gson.fromJson(inputString , Array<Property>::class.java).toList()
println("Please enter a suburb name: ")
val suburbName = command.nextLine()
println("Please enter the postcode: ")
val postcode = command.nextLine()
val userProperty: Property? = packagesArray.find{ it.Locality.toLowerCase().equals(suburbName.toLowerCase()) && it.Pcode == postcode.toInt()}
//sort the list, give the Comparator the current location
Collections.sort(packagesArray, new SortPlaces(userProperty.Latitude, userProperty.Longitude));
}
command.close()
}
I got error: Too many arguments for public open fun <T : Comparable<T!>!> sort(list: (Mutable)List<T!>!): Unit defined in java.util.Collections
at my sort{} function
my userProperty has to be Property? because the find{} method return Property?
Then Collections.sort() can not sort Property? type because the SortPLaces only accept Comparator not Comparator<Property?>
What should I do?
There are multiple errors in your code. To create a new object in Kotlin, you don't write the word new like you do in Java. Also, as you have noticed, find returns a nullable type - Property?. You need to check for nulls when using userProperty. A Property matching the criteria you want may not necessarily be found, after all.
if (userProperty != null) {
Collections.sort(packagesArray, SortPlaces(userProperty.Latitude, userProperty.Longitude))
} else {
// no property is found! Think about what you should do in such a case
}
Since you are sorting the list in line, you should not make an immutable list with toList when you are deserialising the JSON, but rather a MutableList:
val packagesArray = gson.fromJson(inputString, Array<Property>::class.java).toMutableList()
Also, you seem to be using a lot of Java APIs. In Kotlin, a lot of the Java APIs that you are using have more idiomatic Kotlin counterparts. To sort the list, you don't need the SortPlaces class at all. Simply use sortBy on the array, and call your distance function in the lambda.
data class Property(
val pcode: Int,
val locality: String,
val state: String,
val comments: String,
val category: String,
val longitude: Double,
val latitude: Double,
)
fun distance(fromLat: Double, fromLon: Double, toLat: Double, toLon: Double): Double {
val radius = 6378137.0 // approximate Earth radius, *in meters*
val deltaLat = toLat - fromLat
val deltaLon = toLon - fromLon
val angle = 2 * asin(
sqrt(
sin(deltaLat / 2).pow(2.0) +
cos(fromLat) * cos(toLat) *
sin(deltaLon / 2).pow(2.0)
)
)
return radius * angle
}
fun main(args: Array<String>) {
val running = true
while (running) {
val inputStream = File("./src/main/kotlin/suburbs.json").inputStream()
val inputString = inputStream.bufferedReader().use { it.readText() }
val gson = GsonBuilder().create()
val packagesArray = gson.fromJson(inputString , Array<Property>::class.java).toMutableList()
println("Please enter a suburb name: ")
val suburbName = readLine()
println("Please enter the postcode: ")
val postcode = readLine()
val userProperty = packagesArray.find {
it.locality.lowercase() == suburbName?.lowercase() && it.pcode == postcode?.toInt()
}
//sort the list, give the Comparator the current location
if (userProperty != null) {
packagesArray.sortBy {
distance(userProperty.latitude, userProperty.longitude, it.latitude, it.longitude)
}
} else {
// did not find such a property!
}
}
}

Writing an addition visitor function in Kotlin

I'm trying to write a visitor function in Kotlin that adds two integers together. I've been working off of some sample code and I can't figure out what these .value or .visit functions are. It doesn't seem to be declared in the sample code, so I'm unsure how to declare it in my code. Whenever I compile the code, I get an error saying that value is an unresolved reference.
Relevant Kotlin code:
package backend
import org.antlr.v4.runtime.*
import grammar.*
abstract class Data
class IntData(val value: Int): Data() {
override fun toString(): String
= "Int($value)"
}
class Context(): HashMap<String, Data>() {
constructor(parent: Context): this() {
this.putAll(parent)
}
}
abstract class Expr {
abstract fun eval(scope: Context): Data
fun run(program: Expr) {
try {
val data = program.eval(Context())
println("=> ${data}")
} catch(e: Exception) {
println("[err] ${e}")
}
}
}
class IntLiteral(val value: Int): Expr() {
override fun eval(scope:Context): Data
= IntData(value)
}
enum class Op {
Add,
Sub,
Mul,
Div
}
class Arithmetic(
val op: Op,
val left: Expr,
val right: Expr): Expr() {
override fun eval(scope: Context): Data {
val x = (left.eval(scope) as IntData).value
val y = (right.eval(scope) as IntData).value
return IntData(
when(op) {
Op.Add -> x + y
Op.Mul -> x * y
Op.Sub -> x - y
Op.Div -> x / y
}
)
}
}
}
class Compiler: PLBaseVisitor<Expr>() {
val scope = mutableMapOf<String, Expr>()
override fun visitAddExpr(ctx: PLParser.AddExprContext): Expr {
val xValue = this.visit(ctx.x)
val yValue = this.visit(ctx.y)
val result = xValue.value + yValue.value
return IntLiteral(result)
}
}
Relevant Antlr Grammar:
expr : x=expr '+' y=expr # addExpr
| x=expr '-' y=expr # subExpr
| x=expr '*' y=expr # mulExpr
| x=expr '/' y=expr # divExpr
;
Code I'm trying to execute:
val test = """
x=1+2
print(x)
"""
fun parse(source: String): PLParser.ProgramContext {
val input = CharStreams.fromString(source)
val lexer = PLLexer(input)
val tokens = CommonTokenStream(lexer)
val parser = PLParser(tokens)
}
val testTree = parse(source1)
val testTree = parse(source1)
fun execute(program: Expr?) {
if(program == null) {
println("Program is null.")
return
}
try {
val data = program.eval(Context())
println("> ${data}")
} catch(e: Exception) {
println("[err] ${e}")
}
}
execute(testProgram)
Code from sample:
data class NodeValue(val value: Int)
val visitor = object: CalcBaseVisitor<NodeValue>() {
override fun visitAddition(ctx: CalcParser.AdditionContext): NodeValue {
val xValue = this.visit(ctx.x)
val yValue = this.visit(ctx.y)
return NodeValue(xValue.value + yValue.value)
}
override fun visitValue(ctx: CalcParser.ValueContext): NodeValue {
val lexeme = ctx.Number().getText()
return NodeValue(lexeme.toInt())
}
}
You don’t show the code for your program.eval() method.
The eval function would need to create an instance of your Visitor. (You’ve done that and called it visitor).
You also have the root expr node in you program variable.
Now you would have your visitor “visit” that node and save the return value:
val nodeVal = visitor.visit(program)
At that point nodeVal.value will have the result of visiting that expression.
note: since you’re doing the evaluation in your visitor, there’s not really any use for your Arithmetic class (unless you refactor your visitor to use it instead of just doing the math, but I don’t see much value in that as the visitor is already pretty easy to read).

Common methods and operators for inline classes used as units of measurement in Kotlin

I am playing with the idea of using Kotlin's inline classes to express type-safe operations with units of measurement. For example, let's define units for distance, time and speed:
inline class Meters(val v: Float) {
operator fun plus(other: Meters) = Meters(v + other.v)
operator fun times(amount: Float) = Meters(v * amount)
operator fun compareTo(other: Meters) = v.compareTo(other.v)
operator fun div(other: Meters): Float = v / other.v
fun calcSpeed(time: Seconds) = MetersPerSecond(v * time.v)
// operator fun times(time: Seconds) = MetersPerSecond(v / time.v) // clash (for now?)
}
inline class Seconds(val v: Float) {
operator fun plus(other: Seconds) = Seconds(v + other.v)
operator fun times(amount: Float) = Seconds(v * amount)
operator fun compareTo(other: Seconds) = v.compareTo(other.v)
operator fun div(other: Seconds): Float = v / other.v
fun calcSpeed(distance: Meters) = MetersPerSecond(distance.v / v)
}
inline class MetersPerSecond(val v: Float) {
operator fun plus(other: MetersPerSecond) = MetersPerSecond(v + other.v)
operator fun times(amount: Float) = MetersPerSecond(v * amount)
operator fun compareTo(other: MetersPerSecond) = v.compareTo(other.v)
fun calcDistance(time: Seconds) = Meters(v * time.v)
fun calcTime(distance: Meters) = Seconds(distance.v / v)
}
The idea here is to define methods for operations that either:
Leave the unit unchanged (eg: sum, multiplication for a pure
value)
Result in a pure value (eg: division by value of the same
unit)
Result in a value of another defined unit (eg: time * distance = speed)
So that one can write expressions like:
val distance = Meters(1f)
val time = Seconds(1f)
val speed: MetersPerSecond = (distance * 0.5f).calcSpeed(time)
Looking at the operators in the example which fall into cases 1 and 2, I can clearly see a pattern, and I am wondering whether there is a way to define those methods once in a more generic fashion for all types that need this "unit-of-measurement" behavior.
I thought about having a common interface and defining operators as extension functions with generics:
interface UnitOfMeasurement { val v: Float }
operator fun <T: UnitOfMeasurement> T.plus(other: T) = T(v + other.v)
But of course this won't work because I can't instantiate a generic like that. Is there any way to achieve this?
You could make use of a factory function of measurement units, that is reified on type T. Then you use it in your operators:
interface UnitOfMeasurement { val v: Float }
inline class Meter(override val v: Float) : UnitOfMeasurement
inline class Second(override val v: Float) : UnitOfMeasurement
inline fun <reified T : UnitOfMeasurement> create(v: Float): T {
return when (T::class) {
Meter::class -> Meter(v) as T
Second::class -> Second(v) as T
else -> throw IllegalArgumentException("don't know how to create ${T::class}")
}
}
inline operator fun <reified T : UnitOfMeasurement> T.plus(other: T) = create<T>(v + other.v)
fun main() {
val a = Meter(10f)
val b = Meter(5f)
println(a + b)
val c = Second(60f)
val d = Second(30f)
println(c + d)
// println(a + c) // throws IllegalArgumentException
}
Can be tried here

I can't generate a class using Kotlin processor

I'm implementing a processor to generate kotlin code using custom annotations. The problem is that I cannot find a way to relate the annotation to the field it was declared for, and I cannot find a way to understand if a field is of a nullable type. The processor doesn't succeed to generate the code because the getAnnotationsByType doesn't return the annotations for the current field (the list it's empty). Not even the order is good, fields are passed first and the annotations after all the fields.
package it.kfi.xml.binding.processor
import com.google.auto.service.AutoService
import com.squareup.kotlinpoet.*
import it.kfi.xml.binding.annotations.XmlClass
import it.kfi.xml.binding.annotations.XmlProperty
import java.io.File
import java.lang.reflect.Type
import javax.annotation.Nullable
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.Processor
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import javax.lang.model.element.TypeElement
import javax.lang.model.element.VariableElement
import javax.lang.model.type.NullType
import javax.lang.model.type.TypeMirror
import javax.print.DocFlavor
import javax.tools.Diagnostic
import kotlin.reflect.KClass
import kotlin.reflect.full.createType
#AutoService(Processor::class)
class XmlBinder : AbstractProcessor() {
companion object {
const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated"
}
override fun getSupportedAnnotationTypes(): MutableSet<String> {
return mutableSetOf(XmlClass::class.java.name)
}
override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latest()
override fun process(annotations: MutableSet<out TypeElement>?, roundEnv: RoundEnvironment): Boolean {
roundEnv.getElementsAnnotatedWith(XmlClass::class.java)
.forEach {
if (it.kind != ElementKind.CLASS) {
processingEnv.messager.printMessage(Diagnostic.Kind.ERROR, "Only classes can be annotated")
return true
}
processClass(it)
}
return false
}
private fun processClass(element: Element) {
val className = element.simpleName.toString() + "Model"
val packageName = processingEnv.elementUtils.getPackageOf(element).toString()
val classBuilder = TypeSpec.classBuilder(className)
classBuilder.addModifiers(KModifier.PUBLIC)
val initFromXml = FunSpec.builder("initFromXml")
initFromXml.addModifiers(KModifier.PUBLIC)
initFromXml.addParameter(ParameterSpec.builder("xml", String::class).build())
val properties = element.enclosedElements
var x: Int = 1
//Look for elements annotated with XmlField and add those elements to the generated class
for (property in properties) {
val annotation = property.getAnnotationsByType(XmlProperty::class.java)
val v = 10
classBuilder.addProperty(PropertySpec.varBuilder(property.simpleName.toString(), String::class, KModifier.PUBLIC).initializer(v.toString()).build())
initFromXml.addStatement("this.${property.simpleName} = \"${v.toString()}\"")
}
classBuilder.addFunction(initFromXml.build())
val fileName = "kfi_generated_$className"
val file = FileSpec.builder(packageName, fileName).addType(classBuilder.build()).build()
val kaptKotlinGeneratedDir = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME]
file.writeTo(File(kaptKotlinGeneratedDir))
}
}
Can anyone help me found a way to relate annotations to their fields or properties ?