Difference between member function and property - kotlin

What is the difference?
val isFinished: Boolean
get() = actor.actions.size == 0
fun isFinished() = actor.actions.size == 0
I have no idea.
I expect them to be the same.

The first statement defines a property and the second statement defines a method.
Assume you define both in a class Foo.
val foo = Foo()
if(foo.isFinished) {} // property
if(foo.isFinished()) {} // method - see () at invocation
Under the hood, both variants call a function.

Class Property
Your first example is a class property:
class MyClass {
val isFinished: Boolean
get() = actor.actions.size == 0
}
This property defines an (optional) explicit get method, often referred to as a "getter". You could also omit the getter and do:
class MyClass {
val isFinished: Boolean = (actor.actions.size == 0) //parens not necessary
}
If omitted, as shown in the last example, the value will rather be a constant value which isn't re-calculated on each access. Both variants serve different use cases but in most cases, the latter will be sufficient.
Regardless, for a client of this class, the property can be accessed like this:
val mc = MyClass()
mc.isFinished
This shows accessing a property in Kotlin.
Class member function
Functions in Kotlin can also define functions, which can be referred to as member functions. Your second example demonstrates this feature:
class MyClass {
fun isFinished() = actor.actions.size == 0
}
Defining a member function is similar to properties with explicit getters but still different for a client, since they have to invoke a function rather than accessing a property:
val mc = MyClass()
mc.isFinished()
Side Note
Note that the shown function utilizes an expression body which is equivalent to the following block body approach:
class MyClass {
fun isFinished() {
return actor.actions.size == 0
}
}
Learn more about functions here.

Related

Kotlin: Hashmap of interface methods by the implementing class name

I have a list of clases that implement a specific interface. The ability to construct those clases or not is not static (so it's not possible to use when(className)), and can be configured so I want to be able to create some clases or call some methods based on a hashMap of allowed "constructors". Then if the key identifying a class is in present in the hashmap I can call the corresponding method, otherwise I can safely ignore. Let me illustrate:
Let's say I have an interface like
interface Instanceable {
data class Config(
val bar: Whatever
)
fun getIntance(config: Config): Instanceable
}
Then I have several (let's say 10) classes that implement this interface
class Implementation1() : Instanceable {
companion object {
const val ID = "INSTANCE_1"
}
private lateinit var foo: Whatever
override fun getIntance(config: Config) = Implementation1().also{ this#Implementation1.foo = config.bar }
}
I want to create a hashmap of the methods by the identifiers, so later down the lane I can grab the method from the hashMap by the key ID and just invoke() the value if it's there. Something like:
allowedInstances("INSTANCE_1")?.let{ it.invoke(someConfig) }
In order to do this I tried to create a hashMap of methods like this:
private val allowedInstances = mutableHashMapOf<String, Instanceable.(Instanceable.Config)->Instanceable>()
allowedInstances[Instance1.ID] = Instance1::getIntance
allowedInstances[Instance2.ID] = Instance2::getIntance
allowedInstances[Instance4.ID] = Instance4::getIntance
But it fails with:
Type mismatch.
Required: Instanceable.(Instanceable.Config) → Instanceable
Found: KFunction2<Implementation1, Instanceable.Config, Instanceable>
If I create the hashmap directly and let the compiler infer the types like this:
private val allowedInstances = mutableHashMapOf(
Implementation1.ID to Implementation1::getIntance,
Implementation2.ID to Implementation2::getIntance,
Implementation4.ID to Implementation4::getIntance,
)
Checking the type of the hashmap shows:
HashMap<String, out KFunction2<Nothing, Instanceable.Config, Instanceable>>
In fact I can do:
private val allowedInstances = mutableHashMapOf<String, Nothing.(Instanceable.Config)->Instanceable>()
allowedInstances[Instance1.ID] = Instance1::getIntance
allowedInstances[Instance2.ID] = Instance2::getIntance
allowedInstances[Instance4.ID] = Instance4::getIntance
So the actual question is:
Why the function of the second hashMap parameter has Nothing as the receptor? Why I cannot have the interface Instanceable instead?
Edit: Still not good to have the Nothing there:
allowedInstances["INSTANCE_1"]?.let{ it.invoke(Nothing, someConfig) }
//Fails with: Classifier 'Nothing' does not have a companion object, and thus must be initialized here
Edit 2: All of the errors are in compile time
Your function type
Instanceable.(Instanceable.Config) -> Instanceable
is describing an extension function on an instance of Instanceable. You need to omit the receiver from the function type to be able to match your constructors' signature:
(Instanceable.Config) -> Instanceable
Edit: The other half of the problem is that you define getInstance() as a member function of the class. So you have to create an invalid instance of your class to use to create a valid instance, which doesn't make sense.
I would delete the getInstance() function from your interface, and put the equivalent code in the constructor of your class. Then you can define a function type in your Map that constructs your items.
interface Instanceable {
data class Config(
val bar: Whatever
)
// REMOVE this: fun getIntance(config: Config): Instanceable
}
class Implementation1(config: Config) : Instanceable {
companion object {
const val ID = "INSTANCE_1"
}
private val foo: Whatever = config.bar
}
private val allowedInstances = mutableHashMapOf<String, (Instanceable.Config)->Instanceable>()
allowedInstances[Instance1.ID] = ::Implementation1
// and so on...
// If there's an implementation that has no config, you can use a lambda:
class NoConfigImplementation : Instanceable {
companion object {
const val ID = "INSTANCE_2"
}
}
allowedInstances[NoConfigImplementation.ID] = { _ -> NoConfigImplementation() }

Primitive properties for a class in init block - Kotlin

I'm defining a Kotlin class with a number of primitive properties:
class Contract (contractEntity : ContractEntity) EntityDao<ContractEntity> {
var id : Long // <- This is a primitive datatype, needs to be initialized
var concept : String //<- This also needs to be initialized or declared abstract
init{
mapFromEntity(contractEntity)
}
override fun mapFromEntity(entity : ContractEntity){
id = entity.id
concept = entity.concept
}
}
Now, I want those properties to be initialized with the function mapFromEntity() but I'm stuck with the init block because those are not initialized. What could be a good way to achieve what I'm trying?
So far, the best solution suggest to remove the function that maps the class and use the constructor parameter.
class Contract (contractEntity : ContractEntity) EntityDao<ContractEntity> {
var id = contractEntity.id
var concept = contractEntity.concept
}

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
}

How to instantiate a new instance of generic type

In C# you can place a new constraint on a generic to create a new instance of the generic parameter type, is there an equivalent in Kotlin?
Right now my work around is this:
fun <T> someMethod(class : () -> T) {
val newInstance = class()
}
and I'm calling someMethod() like this
someMethod<MyClass>(::MyClass)
but I would like to do something like this:
fun <T : new> someMethod() {
val newInstance = T()
}
Is that possible?
Currently, that's not possible. You can give a thumbs-up for the issue https://youtrack.jetbrains.com/issue/KT-6728 to vote for the addition of this feature.
At least, you can leave out the generic type because Kotlin can infer it:
someMethod(::MyClass)
A solution:
1/ use an inline function with preserved param type (reified type)
2/ in this inline function, invoque the needed constructor using class introspection (reflexion *)
/!\ an inline function can't be nested/embedded in a class or function
Let see how it works on a simple example:
// Here's 2 classes that take one init with one parameter named "param" of type String
//!\ to not put in a class or function
class A(val param: String) {}
class B(val param: String) {}
// Here's the inline function.
// It returns an optional because it could be passed some types that do not own
// a constructor with a param named param of type String
inline fun <reified T> createAnInstance(value: String) : T? {
val paramType = String::class.createType() //<< get createAnInstance param 'value' type
val constructor = T::class.constructors.filter {
it.parameters.size == 1 && it.parameters.filter { //< filter constructors with 1 param
it.name == "param" && it.type == paramType //< filter constructors whose name is "param" && type is 'value' type
}.size != 0
}.firstOrNull() //< get first item or returned list or null
return constructor?.call(value) // instantiate the class with value
}
// Execute. Note that to path the type to the function val/var must be type specified.
val a: A? = createAnInstance("Wow! A new instance of A")
val b: B? = createAnInstance("Wow! A new instance of B")
*) kotlin-reflect.jar must be included in the project
In Android Studio: add to build.gradle(Module: app): implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"