What does "Expecting member declaration" mean? - kotlin

I am creating this class as part of a tutorial for Compose navigation.
sealed class Screens(val route: String) {
object Screen1 : Screens( route: "screen1")
object Screen2 : Screens( route: "screen2")
}
I am getting the error "Expecting member declaration". What does this error mean in simple terms?

It should either be Screens("screen1") or (if you want to use named arguments) Screens(route="screen1"), with a =.
That error is because the syntax you're using (with the colon) is confusing the compiler, it doesn't make sense there

Related

How to loop through Seal Class object without Reflection?

I try to loop through my seal class of
sealed class NavigationItem(val route: String, val icon: Int, val title: String, val color: String) {
object Home : NavigationItem("home", R.drawable.ic_home, "Home", "#FFFF00")
object Music : NavigationItem("music", R.drawable.ic_music, "Music", "#FF00FF")
object Movies : NavigationItem("movies", R.drawable.ic_movie, "Movies", "#00FFFF")
object Books : NavigationItem("books", R.drawable.ic_book, "Books", "#FFAAAA")
object Profile : NavigationItem("profile", R.drawable.ic_profile, "Profile", "#AAAAFF")
}
Using the below
NavigationItem::class.sealedSubclasses.forEach {
it.objectInstance?.apply {
// Do something with each of the object (this)
}
}
However, it complaints
kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath
I want to avoid using Reflection to loop through them, is that possible? Or I have to use Enum for that purpose?
Well, you can try with Enum values() or you must import kotlin-reflection library to your project.
Put this into your dependencies.
impolementation org.jetbrains.kotlin:kotlin-reflect:${Versions.kotlin}
And it will work properly.
One problem of this can be the order of sealedSubclasses. But there are many ways to implement this.
one thing I tried is all the Subclasses have index value and then sort it at the end or you can use mapIndexed pipeline or something.

Cannot access expected class constructor parameters in kotlin multi-platform

I'm currently working on a multi-platform module using kotlin. To do so, I rely on the expect/actual mechanism.
I declare a simple class in Common.kt:
expect class Bar constructor(
name: String
)
I'd like to use the defined class in a common method (also present in Common.kt):
fun hello(bar: Bar) {
print("Hello, my name is ${bar.name}")
}
The actual implementation is defined in Jvm.kt:
actual data class Bar actual constructor(
val name: String
)
The problem is I got the following error inside my hello function
Unresolved reference: name
What am I doing wrong?
Expected classes constructor cannot have a property parameter
Therefore it is necessary to describe the property as a class member with val name: String
Actual constructor of 'Bar' has no corresponding expected declaration
However, for the actual constructor to match the expected declaration the number of parameters has to be the same. That is why the parameter is also added name: String in the constructor in addition to the existence of the property.
expect class Bar(name: String) {
val name: String
}
actual class Bar actual constructor(actual val name: String)
Note: If we leave the constructor empty of the expected class we see how the IDE complains when adding a constructor in the current class for the incompatibility.
GL
It should be val name in the expect part as well, either in the constructor parameter list or as a member property.

btn.setOnClickListener() how does it calls

I am beginner in programing, and I know how btn.setOnClickListener{} function works (curly brackets).
But there is other tipe of function btn.setOnClickListener() - brackets are not curly. I do not know how and when I should use this tipe of functions. How does such type of function calls? I would like to learn more about it but I do not know how to google it
Answer: "If a function has only one parameter, and this is a function, the parentheses can be deleted"
According to : https://antonioleiva.com/lambdas-kotlin-android/
If a function has only one parameter, and this is a function, the parentheses can be deleted
Instead of having empty parentheses, we can better delete them:
view.setOnClickListener { v -> toast("Hello") }
If the function’s last parameter is a function, it can go outside the parentheses
Therefore, we can extract the listener as follows:
view.setOnClickListener() { v -> toast("Hello") }
If we had more parameters, the rest of the parameters would go inside the parentheses, even if these were functions. Only the last parameter can be extracted.
Both types are equivalent:
button.setOnClickListener {
// ......................
}
button.setOnClickListener(View.OnClickListener {
// ......................
})
but the 1st one is the preferred way to go.
Even if you write the 2nd one, if you hover the mouse over View.OnClickListener, Android Studio will pop up this message:
Redundant SAM constructor
and if you press Alt-Enter you will be prompted:
Remove redundant SAM constructor
and if you click on it then View.OnClickListener will be removed.
Again by pressing Alt-Enter you will be prompted:
Move lambda argument out of parentheses
and if you click on it then you will get the 1st type.
So don't worry about it, use the 1st type and you will be fine.
Answer: "If a function has only one parameter, and this is a function, the parentheses can be deleted"
setOnClickListener(Interface i)
This is Method of View Class in Android.
1. setOnClickListener is method of that class which except only interface as a parameter.
2. or else you have to implement that interface in your class like given example.
Go through Anonymous Class implement process.
the thing is that. either you pass interface object or you have to implement onClick method interface OnClickListener.
1. When you want to implement in class use this
btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
2. Pass interface object of onClickListener
appView.setOnClickListener(); ;----> pass interface object

Unmarshalling generic types with Json Spray in Akka Http

I have routes in Akka Http(Scala) project which are basically the same (CRUD operations) except for entities they operate on
I have my Json formats defined in JsonSupport trait like this:
trait JsonSupport extends SprayJsonSupport {
import DefaultJsonProtocol._
implicit val userJsonFormat = jsonFormat3(User)
}
Then I have a route defined which extends this trait, so it works fine if I use a concrete type, but as soon as I have a generic type it fails to compile:
def userRoute[T]: Route =
pathPrefix("users") {
post {
entity(as[T]) { user =>
with error:
could not find implicit value for parameter um: akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller[T]
I suspect that it can't find implicit value because the type is too broad.
What type constraints should I give the T so it would be able to resolve it?
Is there a way to solve it?
Cheers,
Leonti

Setter is invoked before constructor

I am trying to create instances of class HelloWorld, however it does not work. I found that problem is that setter methods called instead of constructor which should initialize variable name, while variable welcome is optional.
I specified getters and setters for both variables. Browser's console is throwing an error about maximum call stack size. If I comment my getters&setters it stops throwing errors.
Could anyone explain me that strange behaviour?
Also there is another problem with mapping. I'm trying to "return" an array if li elements like in React by using .map(). It gives me the result with commas. How can I get rid of them while printing?
This is a link to my code https://codepen.io/CrUsH20/pen/yzMjzL?editors=1010
Updated #1
I fixed the problem with getters&setters by giving a _ sign for private values.
Now I have a problem with
function print() {
if (invitations) {
document.getElementById('result').innerHTML = invitations.map((e)=> {
return `<li>${e.welcome + e.name}</li>`;
});
}
}
Compiler complains that Type 'string[]' is not assignable to type 'string'. in document.getElementById('result').innerHTML while type was not assigned since it is a html element
Update #2
There are solutions:
1# About conflict with constructor and set&get - I changed object's values by adding to their names _. It solved the conflicts.
2# About commas - I added after map .join('') which solved my problem.
The following code (subset of yours) is a compile error:
class HelloWorld {
constructor(public name: string) {
}
set name(e: string) {
this.name = e;
}
get name(): string {
return this.name;
}
}
Garbage in => Garbage out
Fix
Dont use getter / setters and properties with the same name.