Restler remove a level of the body parameters - restler

So let's say I have a class defined with 3 public properties, and then that is the only parameter for the body of my API method. So I end up having to do something like this:
{
"myObj" : {
"param1" : ...
"param2" : ...
"param3" : ...
}
}
Is there some way to not have to specify the myObj part, and just put the class parameters directly?
{
"param1" : ...
"param2" : ...
"param3" : ...
}
If it's the ONLY body parameter this feels much cleaner.

It exactly works that way! Explorer also does that simplification

Related

How to call constructor default lambda using Kotlin Refelction?

Trying to call lambda provided by MyClass constructor using Kotlin Reflection.
data class MyClass(
var magic:Int=2,
var lambdaValue: ()->String = { //trying to call this lambda from reflection
"Working"
},
)
fun main(args: Array<String>) {
val clazz=MyClass::class
val obj=clazz.createInstance()
val kProperty=clazz.memberProperties
clazz.constructors.forEach{cons-> // for each construtor
cons.parameters.forEach{ parameter-> // looping through constructor parameters
val property=kProperty.find { it.name==parameter.name } // finding the exact property
print(parameter.name+" : ")
if(parameter.type.arguments.isEmpty()) // if empty Int,Float
{
println(property?.get(obj))
}else{
println(property?.call(obj)) // unable to call lambda
}
}
}
}
property.call(obj) returns Any which is not invokable. Any solution?
Expected:
magic : 2
lambdaValue : Working
Frankly speaking, I'm not sure what was your idea behind parameter.type.arguments.isEmpty(). It seems unrelated to what you try to do.
If we have a value of the property already, we can simply check its type and if its is a function then invoke it:
val value = kProperty.find { it.name==parameter.name }!!.get(obj)
print(parameter.name+" : ")
when (value) {
is Function0<*> -> println(value())
else -> println(value)
}
I think usefulness of such a code in generic case isn't very high. This code doesn't know what is the function and if it is going to return a value or perform some action, etc. Maybe in your specific case it is more useful.

Kotlin how to use this in "return (object : interface) { }"

class AImpl : A {
override fun createB(): B {
return object : BImpl {
val t = this
override fun createC(): C {
return CBuilderInstance.buildC { // this: CBuilder
this.B = t // type: B
// How can I use 'this#Something' to replace the t.
}
}
}
}
}
class CBuilder {
fun buildC(block: CBuilder.() -> Unit): C {
...
}
}
Sorry that I cannot describe the problem I met.
What can I do to replace "t" in the code?
The IDE give me 2 suggestions, "this" and "this#AImpl", which is not working for this.
According to Kotlin Language Specification - This-expressions, a labeled this-expression can have the following forms:
this#type
this#function
this#lambda
this#outerFunction
The last 3 forms refer to the implicit receiver of functions/lambdas, which is obviously not what you want. You want to refer to the object created by the object literal object : BImpl { ... }.
The spec says (emphasis mine):
this#type, where type is a name of any classifier currently being declared (that is, this-expression is located in the inner scope of the classifier declaration), refers to the implicit object of the type being declared;
And also in Classifier Declarations, it says,
Important: object literals are similar to object declarations and are considered to be anonymous classifier declarations, despite being expressions.
So although object literals are classifier declarations, they do not have a name that we can write after the #.
To conclude, you cannot use a labeled this expression here, without also changing something else.
You can, for example, declare a local class, which has a name:
class AImpl : A {
override fun createB(): B {
class Foo : BImpl {
override fun createC(): C {
return CBuilder.buildC {
this.B = this#Foo
}
}
}
return Foo()
}
}

Kotlin primary constructor calling secondary constructor

Why does this not compile?
class test
{
constructor() {
var a = Date().day
this(a)
}
constructor(a:Int) {
}
}
error is:
Expression 'this' of type 'test' cannot be invoked as a function. The function 'invoke()' is not found.
The suggested fix is to add this:
private operator fun invoke(i: Int) {}
Why?
First, both of these constructors are secondary constructors. A primary constructor is one which is located outside of the body of the class.
Second, as described in the documentation, the correct syntax to call another constructor is as follows:
class Test {
constructor() : this(1) { }
constructor(a: Int) { }
}
class test constructor(){ // primary constructor (The primary constructor is part of the class header: it goes after the class name (and optional type parameters))
constructor(a: Int) : this() { // secondary constructor
}
}
If you class have define primary constructor, secondary constructor needs to delegate to the primary constructor. See here.
I think primary constructor can not be called from secondary constructor.
You can think like this: secondary calls primary and primary calls secondary => endless loop => not possible
In your case, there are 2 secondary constructor, so you can do like
class test {
constructor() : this(Date().day) // I see it quite like Java here https://stackoverflow.com/questions/1168345/why-do-this-and-super-have-to-be-the-first-statement-in-a-constructor
constructor(a: Int) {
}
}
Couple of things are wrong here:
Classes should always use camel-case for their names (test -> Test)
You cannot call another constructor as you tried to (calling this(1) inside of the other constructors body)
I think what you actually want is a being a property and alternatively initialize it with a default value. You could do it like this
class Test(val a: Int) {
constructor() : this(1) // notice how you can omit an empty body
}
or even better, like this:
class Test(val a: Int = 1) // again an empty body can be omitted.
Edit:
If you need to do some calculations, as asked in the comment below Yole's answer:
class Test(val day: Int) {
// you can use any expression for initialization
constructor(millis: Long) : this(Date(millis).day)
}
or if things get more complicated:
class Test(var day: Int) {
// pass something (i.e. 1) to the primary constructor and set it properly in the body
constructor(millis: Long) : this(1) {
// some code
day = // initialize day
}
}

Kotlin, how to assign callback implementation to a variable

I'm trying to assign a callback implementation of an interface (defined inside a class A) to a variabile defined inside another class B. Let's say that class A has the interface OnSomethingHappens which defines a doSomething method.
Inside class B I've defined my callback variable like this:
private lateinit var callback:A.OnSomethingHappens
I need to create an instance of class A passing callback variabile to the constructor in this way:
myinstanceA = A(callback)
I'm trying to assign an instance of an anonymous class that implements A.OnSomethingHappens using this code:
callback = object : A.OnSomethingHappens {
override fun doSomething(..){
//here I put the implementation of this method
}
}
but the compiler says "expecting member declaration" for my callback variable and "name expected" for object.
What I'm doing wrong?
Instead, I'm able to define and at the same time assign the callback variable in this way:
private var callback = object : A.OnSomethingHappens {
override fun doSomething(..){
//here I put the implementation of this method
}
}
Why? Which are the differences and a possible solution?
I'm trying to assign an instance of an anonymous class that implements A.OnSomethingHappens using this code: ...
This should work, but only inside a method:
class B {
private lateinit var callback:A.OnSomethingHappens
fun someMethod() {
callback = object : A.OnSomethingHappens { ... }
}
...
}
Given the error message and that private var compiles (which doesn't inside a method), you are trying to set it directly in the body of the class instead:
class B {
private lateinit var callback:A.OnSomethingHappens
callback = object : A.OnSomethingHappens { ... }
...
}
This is illegal: the only code you can write there is member definitions and init blocks.
Also, if you can initialize callback directly where it's defined or inside init, there's no point to lateinit in the first place.
It's not obvious from the code snippets cut down to such small pieces, but your issue is that you're writing down the assignment inside the body of a class, but not inside a function.
Here's an example of a valid declaration and immediate assignment:
class A {
var x: X? = X()
}
Here's an example of an invalid assignment, which places an arbitrary expression in the body of a class:
class A {
lateinit var x: X
x = X() // expression placed inside the class body, invalid syntax
someFunction() // extra example, calling functions here is invalid in the same way
}
Instead, you could put this initialization inside a function:
class A {
lateinit var x: X
fun initializeX() {
x = X()
}
}
Or inside an initializer block (in this case, you don't even need lateinit):
class A {
var x: X
init {
x = X()
}
}
While I couldn't explain how to solve your exact problem, because I can't quite understand what code is in which class, I hope these examples and explanation helped.
Hmm, let me propose a variant. It's more simple for me:
import android.util.Log
class SomeClass {
fun mainMethod() {
ClassWithCallback(
{ myBackValue: String ->
logMyString(myBackValue)
}
)
//simplify
ClassWithCallback({ logMyString(it) })
}
private fun logMyString(myBackValue: String) {
Log.d("SomeClass", myBackValue)
}
}
class ClassWithCallback(private val myCallBack: (myBackValue: String) -> Unit) {
init {
// we do something here and back it by callback
val myString = "Hello! Pass me back!"
myCallBack.invoke(myString.toUpperCase())
}
}
Using Kotlin lambdas. Hope this will help you.

Passing parameters to a custom getter in kotlin

I have been reading about properties in Kotlin, including custom getters and setters.
However, I was wondering if it is possible to create a custom getter with extra parameters.
For example, consider the following method in Java:
public String getDisplayedValue(Context context) {
if (PrefUtils.useImperialUnits(context)) {
// return stuff
} else {
// return other stuff
}
}
Note that the static method in PrefUtils has to have Context as a parameter, so removing this is not an option.
I would like to write it like this in Kotlin:
val displayedValue: String
get(context: Context) {
return if (PrefUtils.useImperialUnits(context)) {
// stuff
} else {
// other stuff
}
}
But my IDE highlights all of this in red.
I am aware I can create a function in my class to get the displayed value, but this would mean I would have to use .getDisplayedValue(Context) in Kotlin as well instead of being able to refer to the property by name as in .displayedValue.
Is there a way to create a custom getter like this?
EDIT: If not, would it be best to write a function for this, or to pass Context into the parameters of the class constructor?
As far as I know, property getter cannot have parameter. Write a function instead.
You can do this by having a property that returns an intermediate object that has a get and/or set operator with the parameters that you want, rather than returning the value directly.
Having that intermediate object be an inner class instance may be useful for providing easy access to the parent object. However, in an interface you can't use inner classes so in that case you might need to provide an explicit constructor parameter referencing the parent object when constructing your intermediate object.
For instance:
class MyClass {
inner class Foo {
operator fun get(context: Context): String {
return if (PrefUtils.useImperialUnits(context)) {
// return stuff
} else {
// return other stuff
}
}
}
val displayedValue = Foo()
}
...
val context : Context = whatever
val mc : MyClass = whatever
val y: String = mc.displayedValue[context]
You can do for example:
val displayedValue: String by lazy {
val newString = context.getString(R.string.someString)
newString
}