I am trying to get lower case letters from Kotlin Enum class when i pass the object in #QueryValue, but i am getting only upper case letters.
I have an enum in data class for example like below:
enum class StudentName{
#JsonProperty("ram")
RAM,
#JsonProperty("sam")
SAM
}
and i am using that enum like below:
data class StudentParams(
#JsonProperty("studentName")
val studentName: StudentName,
#JsonProperty("age")
val age: Int
)
I am passing this data class as request object in param value like below
#Post(POST_STUDENT_AGE)
fun postStudentAge(
studentParams: StudentParams
): String
so in my URL, request object will go in params like --some url--/&studentName=ram&age=20
i need lower case letters from StudentName enum class here but getting only Upper case. When i pass the request object with #body annotation i am getting lower case letters in the request.
I tried enabling ACCEPT_CASE_INSENSITIVE_ENUMS also but didn't work.
Not sure if this would help, but you can convert the enum to String then invoke the toLowerCase(locale) function,
val ram = StudentName.RAM
val lowerCasedRam = ram.toString().toLowerCase(Locale.current)
when you pass a StudentParams to your postStudentAge,
postStudentAge(StudentParams(StudentName.RAM, 1))
you will do something like this.
fun postStudentAge(
studentParams: StudentParams
) {
val lowerCaseStudent = studentParams.studentName.toString().toLowerCase(Locale.current)
// use lowercase student
}
Calling
Log.e("StudentName", "$lowerCaseStudent")
prints
E/StudentName: ram
You can't just set object as QueryValue. You have to write your own converter. You can find it here.
Another way is write something like this:
#Post
fun postStudentAge(
#QueryValue studentName: StudentName,
#QueryValue studentAge: Int
) {
println(StudentParams(studentName, studentAge))
}
Then you can pass studentName value in lowercase:
localhost:8080?studentName=ram&studentAge=32
And it will work
Related
I have scenario where in I have a "Lookup Table" class that holds getters and setters for multiple class types. As I'm interfacing with a database, I need to provide a way to provide a result boolean and then the class instance which was requested.
For example. Say I have an AssetStatus, StockItemStatus and NominalCode class. I would have to write the following data class for each:
data class LookupResult(
val wasSuccessful: Boolean = false,
val resultClass: AssetStatus? = null,
)
// or
data class LookupResult(
val wasSuccessful: Boolean = false,
val resultClass: StockItemStatus? = null,
)
// or
data class LookupResult(
val wasSuccessful: Boolean = false,
val resultClass: NominalCode? = null,
)
Ideally I don't want to have to repeat myself so I was wondering if I could write one data class (or normal class?) which is able to return one of my multiple Lookup classes?
Initially I thought it would have needed to be Any but after looking into this, that might not be the best case for what I want.
So is there a way of sticking to writing once but not repeating? Or is it something I have to do?
Edit:-
All of my class types would have the following structure (note: I'm using Spring Boot as back end) :
#Entity
#Table(name = "lookup_asset_status")
data class AssetStatus(
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "asset_status_id")
val id: Long? = null,
#Column(name = "asset_status_name")
val name: String = "",
)
...
// Repeat for each entity type
...
If I understand correctly, you want something like this:
data class LookupResult<T>(
val wasSuccessful: Boolean = false,
val resultClass: T? = null,
)
Each of the classes would be written as LookupResult<AssetStatus>, LookupResult<StockItemStatus> and LookupResult<NominalCode>.
If your method needs to be able to return any of those three classes, then it should be declared to return LookupResult<*>. Note that you can only access the members of Any when you access the resultClass of a LookupResult<*>, because you don't know which exact look up result it is.
In a function i have this:
val sunRise = SunEquation(2459622)
binding.timeDisplay.setText("$sunRise.n")
The SunEquation-Class looks like this:
class SunEquation(var jDate: Int,) {
val jYear = 2451545
val ttOffset = .0008
var n = jDate - jYear + ttOffset
}
the button- text that appears is:
com.example.soluna.SunEquation#6d1a94b.n
i would expect a double-value
You have to add curly brackets around the value you want to inject into the String, like this:
binding.timeDisplay.setText("${sunRise.n}")
The shorthand syntax without brackets only works for a single variable, but not
for access to a nested field or other more complex expressions.
In your case, this results in the object itself being injected into the String, which is resembled by com.example.soluna.SunEquation#6d1a94b based on the result of the corresponding toString() call, which defaults to the class name and the reference id of the object. Followed by the literal String .n.
Alternatively, you could extract the value into a val beforehand and reference that.
val customN = sunRise.n
binding.timeDisplay.setText("$customN")
var stringValue: String = "ort"
How to compare stringValue with nameOfCode from Data enum class and get get corresponding code value from enum class in Kotlin in android.
enum class Data(val nameOfCode: String, val code: String) {
WES("wes", "6"),
ORT("ort", "70"),
R("R", "7"),
RON("Ron", "6,7"),
LO("Lo", "6,70"),
OT("ot", "7,70"),
ALL("All", "6,7,7000")
}
Eg: Here string value is "ort" so in enum ort corresponding code value is "70". How to get this value.
You can find the corresponding entry in the enum and get its code, like this:
val code = Data.values().find { it.nameOfCode == nameToBeSearched }?.code
This will give null if nameToBeSearched does not match with any nameOfCode in the enum.
Kotlin 1.4.21
I have a list of Products and I want to transform the price to a formatted string. However, the price doesn't change to the formatted one.
i.e.
orginal price: 1658
expected: "1,658.00"
actual: 1658
This is the class structure
data class Product(
val productName: String,
val price: Double)
Here I am using my list of projects and I want to transform the price.
listOfProjects.map {
it.price.toAmount(2) // extension function that formats to 2 decimal places and converts to a string
}
if (listOfProjects.isNotEmpty()) {
// Do something with the list. However, the price hasn't changed
}
You probably are expecting it to perform in-place formatting. Maybe if you assign an output variable you would be able to get it:
val result = listOfProjects.map { it.price.toAmount(2) }
println(result)
Or if you add a val formattedPrice: String property on the Project class you can define it like this:
val formattedPrice: String = price.toAmount(2)
and then you can use this property in a toString() method for example.
Have you ever tried :
import java.text.DecimalFormat
val dec = DecimalFormat("###.###,##")
In Kotlin, how to get the raw value of the String?
For example,
val value: String = "Adrian"
Expected result:
"Cannot find value: Adrian"
I am coming from Swift and I know in swift it works like this
let value: String = "Adrian"
print("Cannot find \(string.description): \(value)")
Another example in Swift,
let a: String = "b"
print("\(a.description) = \(a)"
///prints "a = b"
Im guessing a String extension is needed given I read the Kotlin String documentation and seems none of the choices provides the expected result.
A simple problem but I really can't solve it:(
This might help you. For this you have to use Kotlin reflection:
Example:
data class Person(val name:String)
fun main(){
val person = Person("Birju")
val prop = person::name
println("Property Name: ${prop.name}")
println("Property Value: ${prop.get()}")
}
How about
println("value :$value")
You don't need concatination operator(+) to concat strings in kotlin