Can i make extensions in Kotlin as in Swift [duplicate] - android

This question already has an answer here:
Does Kotlin has extension class to interface like Swift
(1 answer)
Closed 3 years ago.
Is there any way to make extension of any type in Kotlin like String, Int, Double etc.
Lets say this example in Swift:
extension Int {
func squared() -> Int {
return self * self
}
}
Usage:
var number = 8
print(number.squared())
//Prints 64
Can be formatted for Kotlin?
This question couldn't help me.
Thanks in advance

Yes, Kotlin allows the use of Extensions.
fun Int.squared(): Int{
// Your code
// use `this` parameter to get int value
// return value
}
and the use it anywhere like this:
val squared = 3.squared()
Import statement will be automatically included if you are trying to
use an extension

Extension function:
Integer.squared() : Int{
return this*this
}
Usage:
val squared = 3.squared()

Yes, in Kotlin you would do it like this
fun Int.squared() : Int = this * this

Related

Haw to use variable instead of real property name to describe property in Kotlin

There are a lot of similar questions, but I still can't find out right answer.
In Jawa square brackets works i think, but in Kotlin?
data class source (
val npk : Int = 0,
val name : String = "",
val coa : String = ""
)
fun main() {
var sourceList : MutableList<source> = mutableListOf(source(1, "Uno", "one"),
source(2, "Dues", "two"),
source(3, "Tres", "three"))
sourceList.forEach { source -> println(source.name)} // haw to use variable instead "name"?
val variable = "name"
// sourceList.forEach { source -> println(source.$variable)} Is there construction like this possible in KOTLIN?
Without code changes on your class it's only possible via reflection API. Not usually recommended as it can be slower, and is more error prone.
See this answer for an example on how reflection can be used to achieve that : https://stackoverflow.com/a/35539628/3801327
I'd recommend you to go with the solution that CommonsWare suggested in the comment ( adding get operator ) instead

Kotlin - Set #Annotations . to function return types?

Is there a way to use annotations to declare a return condition for kotlin functions?
For example, I want to tell lint that my function will return an Android resource id at:
fun getImageId(): Int
I would want something as:
fun getImageId(): #DrawableRes Int
which fails
I thought it would make sense (I believe is possible in Java), because I may have something as:
fun setImage(#DrawableRes res: Int) {
myImageView.setImageResource(res)
}
and call it as:
setImage(getImageId())
So that it has a chain of validations that the given int is actually a Res Id
You can do it with:
#DrawableRes
fun getImageId(): Int

How to return outside of forEach in Kotlin? [duplicate]

This question already has answers here:
How do I do a "break" or "continue" when in a functional loop within Kotlin?
(2 answers)
Closed 4 years ago.
I hope to return to the line aa# logError("Done") outside forEach, but return#aa doesn't work, and break#label doesn't work too.
And more, if you use return, it will be return outside the fun lookForAlice !
data class Person(val name: String, val age: Int)
val people = listOf(Person("Paul", 30), Person("Alice", 29), Person("Bob", 31))
fun lookForAlice(people: List<Person>) {
people.forEach label#{
logError("Each: "+it.name)
if (it.name == "Alice") {
logError("Find")
return#aa //It's fault
}
}
aa# logError("Done")
}
lookForAlice(people)
Use the traditional way "for-each" loop.
i.e. change
people.forEach label#{
to
for (it in people) {
and change return to break.
NOTE: Read these articles about `return` in `.forEach()`
`break` and `continue` in `forEach` in Kotlin
How do I do a "break" or "continue" when in a functional loop within Kotlin? (The question may be a duplicate of this link)
You want to use find instead. It'll return Person?. So you can just check if it's null, or not. If not, you found Alice.
data class Person(val name: String, val age: Int)
val people = listOf(Person("Paul", 30), Person("Alice", 29), Person("Bob", 31))
val alice: Person? = findAlice(people)
fun findAlice(people: List<Person>): Person? {
return people.find { it.name == "Alice" }
}

Kotlin equivalent of Java's equalsIgnoreCase

What is the equivalent of Java equalsIgnoreCase in Kotlin to compare String values?
I have used equals but it's not case insensitive.
You can use equals but specify ignoreCase parameter:
"example".equals("EXAMPLE", ignoreCase = true)
As per the Kotlin Documentation :
fun String?.equals(
other: String?,
ignoreCase: Boolean = false
): Boolean
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/equals.html
For Example:
val name: String = "Hitesh"
when{
name.equals("HITESH", true) -> {
// DO SOMETHING
}
}
#hluhovskyi's answer is correct, however to use it on EditText or TextView, use following -
etPassword.text.toString().equals(etConfirmPassword.text.toString(), ignoreCase = true)
In my case,
string1.contains(string2, ignoreCase = true)
This worked for me.
Becase I'm using like a search function here.
Normally, you don't need to find alternatives since Kotlin reuses existing Java types like String. Actually, these types are mapped to Kotlin internal types. In the case of String it looks like this:
java.lang.String -> kotlin.String
Therefore, the desired method equalsIgnoreCase would only be available if it was also provided in kotlin.String, which isn’t. The Kotlin designers decided to provide a more generic equals function that let's you specify the case insensitivity with a boolean parameter.
You can use the Java String class at any time if that's really necessary (it's not recommended, IntelliJ will complain about this):
("hello" as java.lang.String).equalsIgnoreCase("Hello")
With the help of an extension function, we could even add the functionality to the kotlin.String class:
fun String.equalsIgnoreCase(other: String) =
(this as java.lang.String).equalsIgnoreCase(other)
You could make an extension method:
/**
* Shortcut to compare strings while ignoring case
*/
fun String.similarTo(aString: String): Boolean {
return equals(aString,true)
}
Usage:
val upperCase = "ϴẞ"
val lowerCase = "θß"
if (upperCase.similarTo(lowerCase)) {
// Do your thing…
}

Is it possible to get a Kotlin subclass type from within a superclass?

I'm trying to figure out if something is possible. Generally, what I'm trying to do is get a class type of a subclass from within the companion object of the superclass ... In the snipped below, treat the __ as what I need
companion object
{
fun fromSnapshot(snapshot: DataSnapshot): __
{
val model = snapshot.getValue(__)
model.key = snapshot.key
// ...
return model
}
}
Some background ... DataSnapshot is from Firebase, and snapshot.getValue() takes a Class<T>. If I were trying to create an instance of, say, a TestModel, code would be as follows
companion object
{
fun fromSnapshot(snapshot: DataSnapshot): TestModel
{
val model = snapshot.getValue(TestModel::java.class)
model.key = snapshot.key
// ...
return model
}
}
I'm not really sure if what I'm asking is possible in Kotlin. I'm pretty sure it isn't in Java. I hate to mention it, but in Swift, this would be accomplished with what I call "big-S self," or Self, which is the class type of instance self. If you don't know Swift, self is equivalent to Java and Kotlin's this.
Any help would be hugely appreciated!
From your code, it seems to be a very generic function. It doesn't matter what T is and in which companion object this function lives, so I have another version:
inline fun <reified T : FirebaseModel> DataSnapshot.toModelOfType() =
getValue(T::class.java).also { it.key = this.key}
It can be used like this:
someSnapshot.toModelOfType<SomeFirebaseModel>()
instead of your
FirebaseModel.fromSnapshot<SomeFirebaseModel>(someSnapshot)
or with imports
fromSnapshot<SomeFirebaseModel>(someSnapshot)
I prefer mine because it's shorter than your version without imports and more fluent than your version with imports.
I personally suggest Prefer extension functions over Java style utility functions.
Even though I sat on this for days without posting a question, I figured it out less than an hour after posting this question. This can be accomplished with a reified generic type, which allows for usage of the generic type from within a function, however these can only be used as inline functions. Here's my solution
companion object
{
inline fun <reified T : FirebaseModel> fromSnapshot(snapshot: DataSnapshot): T
{
val model = snapshot.getValue(T::class.java)
model.key = snapshot.key
return model
}
}

Categories

Resources