Tertiary operator in kotlin [duplicate] - android

This question already has answers here:
How to write ternary conditional operator?
(33 answers)
Closed 3 years ago.
How do we use ternary operator in Kotlin?
I have tried using ternary operator in same manner that we use in java but I got a lint error in it:
var myVariable = (condition == true) ? value1 : value2

// Valid Kotlin, but invalid Java/C#/JavaScript
var v = if (a) b else c
Alternative:
when(a) {
true -> b
false -> c
}
Hope this helps. Good luck.

Related

I am trying to disable my login button if the task is scuccefull [duplicate]

This question already has answers here:
Why do I get "unresolved reference" error for my view's name/ID when I type it in Kotlin?
(2 answers)
Closed 1 year ago.
I am new to kotlin,
sorry in advance if my formatting is shit
following a tutorial but when I use the
btn_register_rg.isEnabled = false
btn_register_rg.alpha = 0.5f
button in my XML :
android:id="#+id/btn_login_log"
codes it shows me that unresolved reference although am using it my other functions like (in the same fragment)
view.findViewById<Button>(R.id.btn_login_log).setOnClickListener(){
validateForm()
that works just fine, but in this, it shows unresolved references and is colored red although the tutorial am following doesn't face this issue
private fun firebaseSignIn(){
//------> btn_login_log.isEnabled = false
//------> btn_login_log.alpha = 0.5f
fAuth.signInWithEmailAndPassword(username.text.toString(),
password.text.toString()).addOnCompleteListener(){
task ->
if(task.isSuccessful){
Toast.makeText(context,"Login Succesful ",Toast.LENGTH_SHORT).show()
var navHome = activity as FragmentNavigation
navHome.navigateFragment(HomeFragment(),addTostack = true)
}
else{
//------> btn_login_log.isEnabled = false
//------> btn_login_log.alpha = 1.5f
Toast.makeText(context, task.exception?.message,Toast.LENGTH_SHORT).show()
}
}
}
When task is successful try to put below lines for disable button
btn_login_log.isEnabled = false
btn_login_log.isClickable = false

Converting Empty EditText to Integer Android Studio [duplicate]

This question already has answers here:
How to convert String to Int in Kotlin?
(11 answers)
Closed 1 year ago.
I have an EditText which will take a number from the user and save it as sharedPreferences. I have two Buttons to load and save and a TextView to display a saved data. Everything works fine but if the user enters nothing and saves, the app crashes. Here's the Kotlin code,
override fun onClick(p0: View?) {
val sharedPreferences=getSharedPreferences("key", Context.MODE_PRIVATE)
when(p0!!.id){
//saves user data
R.id.btn_save->{
val userAge = Integer.parseInt(ageInput.text.toString()) //the problem is here
val editor=sharedPreferences.edit()
editor.putInt("age",userAge)
editor.apply()
}
//loads or displays user data
R.id.btn_load->{
val age=sharedPreferences.getInt("age",0)
showTv.text="Age: $age"
}
}
}
Use toIntOrNull() instead. Instead of throwing an exception on invalid input, it returns null. Then you can use the Elvis operator to provide the default to use when it's null.
val userAge = ageInput.text.toString().toIntOrNull() ?: 0
You should avoid the Java primitive wrapper classes like Integer when using Kotlin.

" ? " in Kotlin Variable.. what's the purpose on this?

I'm on learning basics of Kotlin language for Android Development :), i'm looking on some Kotlin syntax examples and i found out this example below.. the thing that i don't know what is purpose with the ? code.. i'm trying to find on Google but i can't understand completely what they explain, maybe you can help me with your explanation / your example on this one ? I'll appreciate that :)
Example :
fun main() {
val myName :String? = "Maura"
println("Your name is $myName")
val myAge :Int? = 18
println("Your age is $myAge")
}
Its null safety. Basically Int? represents nullable Int, while Int on its own is non-null.
var a: Int = 5
a = null // error
var b: Int? = 5
a = null // :)
In case you have null in your code, you cannot use them directly, if you want to for example call any function in them you have to follow null-safety: Use ?. safecall operator, or !!. null assertion operator (usually shouldn't use).
val c = a.plus(4) // :)
val d = b.plus(4) // Hold on, I'm null you can't use "." on me :P
val e = b?.plus(4) // Ok, if b is not null, add 4 and store that to e, otherwise store null to e
val f = b!!.plus(4) // Hmm, if b was not null I'll add 4 to it and store to f, otherwise I'll crash your program throwing NPE
In contrast to this the type of e would be Int? as you've already read the thing. But what if you want to assign it a default value, easy use the elvis operator (?:):
val g = b?.plus(4) ?: 4 // if b is not null add 4 to it and store otherwise store 4 :)
Edit: The code in your sample works because there's String template calls .toString() and it is defined as fun Any?.toString() i.e. defined on a nullable receiver. So b.toString is valid though can be confusing.
println("Your age is $myAge")
// is same as
println("Your age is" + myAge.toString())
// toString is an extension function valid for nullable types, though member functions aren't :)
well, this is null safety feature of Kotlin lang (awesome btw.)
in short: ? next to type of variable/value means that this variable/value may be null. don't use it so often, it kind-of protects you from NullPointerExceptions, pretty often bug-cause in Java. also in your simple case it is unnecessary
var myName :String? = null // this is possible
var mySecondName :String = null // this isn't possible, build error
var myThirdName :String = "never null"
myThirdName = null // build error, this variable can't be null
myName = myName.replace("a", "b")
// build error above, trying to access nullable variable straightly
myName = myName?.replace("a", "b")
// null safety with ?, if myName is null it won't be executed and myName stay null
myThirdName = myThirdName.replace("a", "b") // this is possible
myThirdName = myThirdName?.replace("a", "b")
// this is also possible, but you will get a warning that ? is unnecessary

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

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

Ternary operator in kotlin [duplicate]

This question already has answers here:
How to write ternary conditional operator?
(33 answers)
Closed 4 years ago.
I can write in java
int i = 10;
String s = i==10 ? "Ten" : "Empty";
Even I can pass it in method parameter.
callSomeMethod(i==10 ? "Ten" : "Empty");
How do I convert it to kotlin? Lint shows error when writing same thing in kotlin.
callSomeMethod( if (i==10) "Ten" else "Empty")
Discussion about ternary operator:
https://discuss.kotlinlang.org/t/ternary-operator/2116/3
Instead of
String s = i==10 ? "Ten" : "Empty";
Technically you can do
val s = if(i == 10) "Ten" else "Empty"
val s = when {
i == 10 -> "Ten"
else -> "Empty"
}
val s = i.takeIf { it == 10 }?.let { "Ten" } ?: "Empty"
// not really recommended, just writing code at this point
val s = choose("Ten", "Empty") { i == 10 }
inline fun <T> choose(valueIfTrue: T, valueIfFalse: T, predicate: () -> Boolean) =
if(predicate()) valueIfTrue else valueIfFalse
You can create an extension function with generic for boolean value
fun <T> Boolean.elvis( a :T, b :T ): T{
if(this) // this here refers to the boolean result
return a
else
return b
}
and now you can use it for any boolean value (cool Kotlin)
// output
System.out.print((9>6).elvis("foo","bar")) foo
System.out.print((5>6).elvis("foo","bar")) bar
Extensions in kotlin
As the original question was using the term 'Elvis operator' it may be a good idea to provide a short comparison with the ternary operator.
The main difference between ternary operator and Elvis operator is that ternary is used for a short if/else replacement while the Elvis operator is used for null safety, e.g.:
port = (config.port != null) ? config.port : 80; - a shortcut for an if/then/else statement
port = config.port ?: 80 - provides a default value to be used in case the original one is null
The examples look very similar but the Ternary operator can be used with any type of boolean check while the Elvis operator is a shorthand for use config.port if it's not null else use 80 so it only checks for null.
Now, I think Kotlin doesn't have a ternary operator and you should use an if statement like so - s = if (i==10) "Ten" else "Empty"

Categories

Resources