Kotlin Server Ktor Exposed: how to nullable optional Fields - kotlin

I have this function on my Ktor + Exposed App.
override suspend fun createNewCourse(course: CourseModel): Flow<CourseModel> {
transaction {
CoursesTable.insert {
it[requiredCourseId] = course.requiredCourse?.id!!
it[category] = course.category?.id!!
it[isPopular] = course.isPopular == true
it[position] = course.position
it[nameEN] = course.name.en
it[warningEN] = course.warning.en
}
}
It doesn't compile.
Sometimes some variables (like "warningEN") can be null and I dont want to insert nothing for this field.
How to make it?
Type mismatch.
Required:TypeVariable(S) Found: String?

My solution:
it[position] = course.position?.let { course.position!! } ?: null

Related

ktor plugins: require configuration values

I was wondering if there is a way to require configuration parameters when making custom plugins? My current hack around is to catch it at runtime
class PluginConfiguration {
var someConfig: String? = null
}
val MyPlugin =
createApplicationPlugin(name = "MyPlugin", createConfiguration = ::PluginConfiguration) {
val someConfig = pluginConfig.someConfig
pluginConfig.apply {
if (someConfig == null) { // catch here
throw java.lang.Exception("Must pass in someConfig")
}
onCallReceive { call ->
// do stuff
}
}
}
but it would be nice if there was a way for the compiler to catch.
My use case for not wanting defaults is that I want to pass in expensive objects that are managed with dependency injection
I think it's not possible with PluginConfiguration API.
But there should be no problem in converting MyPlugin to a function, which will require a parameter to be specified:
fun MyPlugin(someRequiredConfig: String) =
createApplicationPlugin(name = "MyPlugin", createConfiguration = ::PluginConfiguration) {
val someConfig = someRequiredConfig
pluginConfig.apply {
onCallReceive { call ->
// do stuff
}
}
}
// ...
install(MyPlugin("config"))

incrementing hash map count in Kotlin

I have the function below. However, when I pass a string to it, I get the following error:
error: operator call corresponds to a dot-qualified call 'charCountMap.get(c).plus(1)' which is not allowed on a nullable receiver 'charCountMap.get(c)'. charCountMap.put(c, charCountMap.get(c) + 1)
private fun characterCount(inputString:String) {
val charCountMap = HashMap<Char, Int>()
val strArray = inputString.toCharArray()
for (c in strArray)
{
if (charCountMap.containsKey(c))
{
charCountMap.put(c, charCountMap.get(c) + 1)
}
else
{
charCountMap.put(c, 1)
}
}
}
The Kotlin Standard Library has groupingBy and eachCount for this purpose, you don't need to do any of this manually:
private fun characterCount(inputString:String) {
val charCountMap : Map<Char, Int> = inputString.groupingBy { it }.eachCount()
}
Note that I put the type on charCountMap for clarity, but it can be left off and inferred.
There is nice compute method in HashMap for this:
private fun characterCount(inputString:String) = hashMapOf<Char, Int>().also { charCountMap ->
inputString.forEach { charCountMap.compute(it) { _, v -> if (v == null) 1 else v + 1 } }
}
Both the other answers are correct. Todd's answer is right, you don't need to write a function for this. Just use the standard library. And if you are going to write a function that updates maps, Михаил Нафталь's suggestion to use compute() to handle updating existing values is also good.
However, if you're just doing this an an exercise, here are three suggestions to fix/improve your algorithm:
Instead of get(), use getValue(), which does not return null. It will raise an exception if the element does not exist, but you already checked for that.
Use the [] operator instead of put() (no need to, it's just nicer syntax).
You don't need to call toCharArray() because Strings are already iterable.
if (charCountMap.containsKey(c))
{
charCountMap[c] = charCountMap.getValue(c) + 1
}
else
{
charCountMap[c] = 1
}
Rewriting the whole thing using standard formatting:
fun characterCount(inputString: String): Map<Char, Int> {
val charCountMap = mutableMapOf<Char, Int>()
for (c in inputString) {
if (charCountMap.containsKey(c)) {
charCountMap[c] = charCountMap.getValue(c) + 1
} else {
charCountMap[c] = 1
}
}
return charCountMap
}

How to handle nullable types in generic class

I want to write a Promise class in kotlin. This class uses a generic type. The type can also be a nullable type. When I call the consumer, the value can be null, if the genereic type is nullable. If not the value must be set to an object. The kotlin compiler shows me following message:
Smart cast to 'T' is impossible, because 'value' is a mutable property that could have been changed by this time
I understand why this message appears but I am sure, that the value must be correct at this moment. How can I compile this class? I tried to force to access the value with !! but then my test with null will fail with a NPE.
java.lang.NullPointerException
at test.Promise.resolve(App.kt:20)
at test.AppTest.testPromiseNull(AppTest.kt:31)
class Promise<R> {
private var resolved = false
private var value: R? = null
var then: Consumer<R>? = null
fun resolve(r: R) = synchronized(this) {
if (resolved) error("Promise already resolved!")
value = r
resolved = true
then?.accept(value) // Smart cast to 'T' is impossible, because 'value' is a mutable property that could have been changed by this time*
}
fun then(consumer: Consumer<R>) = synchronized(this) {
if (then != null) error("Just one consumer is allowed!")
then = consumer
val value = value
if (resolved) {
consumer.accept(value) // Smart cast to 'T' is impossible, because 'value' is a mutable property that could have been changed by this time*
}
}
}
#Test fun testPromise() {
val promise = Promise<String>()
var resolved = false
promise.then {
assertEquals(it, "hello" )
resolved = true
}
promise.resolve("hello")
assert(resolved)
}
#Test fun testPromiseNull() {
val promise = Promise<String?>()
var resolved = false
promise.then {
assertNull(it)
resolved = true
}
promise.resolve(null)
assert(resolved)
}
UPDATE
I created a little help function
private fun <T> uncheckedCast(t: T?): T {
#Suppress("UNCHECKED_CAST")
return t as T
}
For your resolve function, you already have the immutable parameter value you can use instead.
fun resolve(r: R) = synchronized(this) {
if (resolved) error("Promise already resolved!")
value = r
resolved = true
then?.accept(r)
}
In the other case, since you know more than the compiler, you can do an explicit cast, and suppress the warning.
fun then(consumer: Consumer<R>) = synchronized(this) {
if (then != null) error("Just one consumer is allowed!")
then = consumer
if (resolved) {
#Suppress("UNCHECKED_CAST")
consumer.accept(value as R)
}
}

How can i call an interface in kotlin?

I do not have a project in my work and they have asked me to give me a pass, but after passing the whole project, there is a part that has given me a code error at the moment. Clearly it's my first time in Kotlin and I have no idea, but I do have an idea. I tried to solve it and I have not succeeded. So I was asking for help. I get an error right at the beginning of the
= SpeechService.Lintener {
Here the code
private val mSpeechServiceListener = SpeechService.Listener { text: String?, isFinal: Boolean ->
if (isFinal) {
mVoiceRecorder!!.dismiss()
}
if (mText != null && !TextUtils.isEmpty(text)) {
runOnUiThread {
if (isFinal) {
if (mText!!.text.toString().equals("hola", ignoreCase = true) || b == true) {
if (b == true) {
mText!!.text = null
mTextMod!!.text = text
repro().onPostExecute(text)
random = 2
} else {
b = true
mText!!.text = null
val saludo = "Bienvenido, ¿que desea?"
mTextMod!!.text = saludo
repro().onPostExecute(saludo)
}
}
} else {
mText!!.text = text
}
}
}
}
and here the interface
interface Listener {
fun onSpeechRecognized(text: String?, isFinal: Boolean)
}
Please, help me. the error is "Interface Listener does not have constructor"
The SpeechService.Listener { } syntax for SAM interfaces is only possible when the interface is written i Java (see https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions). Because the interface is written in Kotlin, you have to write it like this:
private val mSpeechServiceListener = object : SpeechService.Listener {
override fun onSpeechRecognized(text: String?, isFinal: Boolean) {
// Code here
}
}
You don't really need the SpeechService.Listener interface in Kotlin though. You could just use a lambda function. This depends on whether the interface comes from a library or if you've written it yourself though.
private val mSpeechServiceListener: (String?, Boolean) -> Unit = { text, isFinal ->
// Code here
}

Kotlin general setter function

I am new to kotlin. I wonder if this is possible
I wish to create a function that will change the value of the properties of the object and return the object itself. The main benefit is that I can chain this setter.
class Person {
var name:String? = null
var age:Int? = null
fun setter(propName:String, value:Any): Person{
return this.apply {
try {
// the line below caused error
this[propName] = value
} catch(e:Exception){
println(e.printStackTrace())
}
}
}
}
//usage
var person = Person(null,null)
person
.setter(name, "Baby")
.setter(age, 20)
But I get error "unknown references"
This question is marked as duplicate, however the possible duplicate question specifically want to change the property of "name", but I wish to change anyProperty that is pass from the function to object. Can't seem to connect the dot between two questions. #Moira Kindly provide answer that explain it. thankyou
Why not just simplify your answer to
fun setter(propName: String, value: Any): Person {
val property = this::class.memberProperties.find { it.name == propName }
when (property) {
is KMutableProperty<*> ->
property.setter.call(this, value)
null ->
// no such property
else ->
// immutable property
}
}
Java reflection isn't needed, its only effect is to stop non-trivial properties from being supported.
Also, if you call it operator fun set instead of fun setter, the
this[propName] = value
syntax can be used to call it.
After googling around, I think I can provide an answer, but relying on java instead of kotlin purely. It will be great if someone can provide a better answer in kotlin.
class Person(
var name: String,
val age: Int
){
fun setter(propName: String, value: Any): Person{
var isFieldExistAndNotFinal = false
try{
val field = this.javaClass.getDeclaredField(propName)
val isFieldFinal = (field.getModifiers() and java.lang.reflect.Modifier.FINAL == java.lang.reflect.Modifier.FINAL)
if(!isFieldFinal) {
// not final
isFieldExistAndNotFinal = true
}
// final variable cannot be changed
else throw ( Exception("field '$propName' is constant, in ${this.toString()}"))
} catch (e: Exception) {
// object does not have property
println("$e in ${this.toString()}")
}
if(isFieldExistAndNotFinal){
val property = this::class.memberProperties.find { it.name == propName }
if (property is KMutableProperty<*>) {
property.setter.call(this, value)
}
}
return this;
}
}
usage like this
person
.setter(propName = "age", value = 30.00)
.setter(propName = "asdf", value = "asdf")
.setter(propName = "name", value = "A Vidy")
You have error because when you do this[propName] = value you are trying to use this as a list, but it is not a list, it is a Person and it doesn't overload the [] operator.
What you can do is to add a check for the property that is setted:
class Person {
privavar name:String? = null
var age:Int? = null
fun setter(propName:String, value:Any): Person{
return this.apply {
if (propName == "name" && value is String?) {
it.name = value as String?
} else if (propName == "age" && value is Int?) {
it.age = value as Int?
} else {
// handle unknown property or value has incorrect type
}
}
}
}
Another more dynamic solution without reflection:
class Person {
private var fields: Map<String, Any?> = HashMap()
fun setter(propName:String, value:Any): Person{
return this.apply {
it.fields[propName] = value;
}
}
fun getName() = fields["name"]
}
If you want to get rid of the getters as well then you need to use reflection.