What is your thought process to decide whether to use ?.let or ?.also

I always struggle to decide whether to use ?.let or ?.also most of the time. For instance, the 2 code snippet will have equivalent behaviour.

Use ?.let

 fun String?.isNullOrTrimEmpty(): Boolean { return this?.trim().isNullOrEmpty() } val theme: Theme by mutableLazy { val sharedPreferences = XXXApplication.instance.getSharedPreferences() val moshi = Moshi.Builder().build() val jsonTheme = sharedPreferences.getString(THEME, null) if (!jsonTheme.isNullOrTrimEmpty()) { jsonTheme?.let { nonNullJsonTheme -> moshi.adapter(Theme::class.java).fromJson(nonNullJsonTheme)?.let { theme -> return@mutableLazy theme } } } return@mutableLazy PREFERRED_THEME } 

Use ?.also

 fun String?.isNullOrTrimEmpty(): Boolean { return this?.trim().isNullOrEmpty() } val theme: Theme by mutableLazy { val sharedPreferences = XXXApplication.instance.getSharedPreferences() val moshi = Moshi.Builder().build() val jsonTheme = sharedPreferences.getString(THEME, null) if (!jsonTheme.isNullOrTrimEmpty()) { jsonTheme?.also { nonNullJsonTheme -> moshi.adapter(Theme::class.java).fromJson(nonNullJsonTheme)?.also { theme -> return@mutableLazy theme } } } return@mutableLazy PREFERRED_THEME } 

By using the above example, may I know which one is the more accurate code snippet?

May I know, what is your thought process to decide whether to use ?.let or ?.also

Thanks.

submitted by /u/yccheok
[link] [comments]

Continue ReadingWhat is your thought process to decide whether to use ?.let or ?.also

Kotlin Beginner – Help Needed

When using functions in Kotlin, I am trying to get one function to calculate from the other as a step by step process. Can anyone give me any ideas as to why I am not getting an output at the end of it.

Current code used:

fun main() {

var result = efficiencyStage4()
println(result)
efficiencyCalculator()
efficiencyStage1()
efficiencyStage2()
efficiencyStage3()
efficiencyStage4()

}
fun efficiencyCalculator() {
println(“Enter Current Efficiency”)
val efficiencyNo = readln()
val efficiencyNoInt = efficiencyNo.toInt()
println(“Enter Total Hours of Production Time a week”)
val totalProductionHrs = readln()
val totalProductionHrsInt = totalProductionHrs.toInt()
println(“Enter Total number of Production Lines”)
val totalProductionLines = readln()
val totalProductionLinesInt = totalProductionLines.toInt()
println(“Enter the number of weeks a year producing”)
val totalWeeks = readln()
val totalWeeksInt = totalWeeks.toInt()
println(“Enter the company turnover for the year”)
val yearlyTurnover = readln()
val yearlyTurnoverInt = yearlyTurnover.toInt()
}

fun efficiencyStage1(totalProductionHrsInt: Int, efficiencyNo: Int, ): Int {
val efficiencyHrs = totalProductionHrsInt / 100 * efficiencyNo
return efficiencyHrs
}

fun efficiencyStage2(efficiencyHrs: Int, totalProductionLinesInt: Int): Int {
val totalEfficiencyHrs = efficiencyHrs * totalProductionLinesInt
return totalEfficiencyHrs
}

fun efficiencyStage3(totalEfficiencyHrs: Int, totalWeeksInt: Int): Int {
val yearlyEfficiencyHrs = totalEfficiencyHrs * totalWeeksInt
return yearlyEfficiencyHrs
}

fun efficiencyStage4(yearlyEfficiencyHrs: Int, yearlyTurnoverInt: Int): Int {
val hourlyinefficiency = yearlyTurnoverInt / yearlyEfficiencyHrs
return hourlyinefficiency
println(yearlyEfficiencyHrs)

I think I may be missing a piece of code that will allow me to display the total yearly efficiency hrs

submitted by /u/jgreen1984
[link] [comments]

Continue ReadingKotlin Beginner – Help Needed

Upload video file to pre-signed S3 URL with partial upload mechanism

I’m currently in need of uploading a large video file, around 500Mb, from an API using a pre-signed S3 URL. However, I want to be able to perform a partial upload and utilize resumable upload functionality so that in case of a connection failure, it can resume uploading from where it left off without starting over.

Have any of you encountered this issue before? Could you please share with ideas me to solve this problem?
Thank you very much.

submitted by /u/mass-101
[link] [comments]

Continue ReadingUpload video file to pre-signed S3 URL with partial upload mechanism

Feedback Request: Implementing a mutableLazy Delegate in Kotlin for Thread-Safe Mutable Properties

I’ve been exploring Kotlin’s lazy functionality and realized it’s primarily designed for immutable variables. However, I needed a similar mechanism for mutable properties. As a result, I devised a mutableLazy delegate pattern that aims to support mutability while preserving thread safety through double-checked locking. Here’s the implementation:

 import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty fun <T> mutableLazy(initializer: () -> T): MutableLazy<T> { return MutableLazy(initializer) } class MutableLazy<T>(initializer: () -> T) : ReadWriteProperty<Any?, T> { companion object { private object UNINITIALIZED } u/Volatile private var value: Any? = UNINITIALIZED private var initializer: (() -> T)? = initializer private val lock = Any() override fun getValue(thisRef: Any?, property: KProperty<*>): T { val _v1 = value if (_v1 != UNINITIALIZED) { u/Suppress("UNCHECKED_CAST") return _v1 as T } return synchronized(lock) { val _v2 = value if (_v2 != UNINITIALIZED) { u/Suppress("UNCHECKED_CAST") _v2 as T } else { val typedValue = initializer!!() value = typedValue initializer = null // Clear the initializer to allow garbage collection of the lambda typedValue } } } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { synchronized(lock) { this.value = value } } } 

Usage example:

 object XXXOptions { private const val THEME = "THEME" val theme: Theme by mutableLazy { val sharedPreferences = XXXApplication.instance.getSharedPreferences() val moshi = Moshi.Builder().build() val jsonTheme = sharedPreferences.getString(THEME, null) if (!jsonTheme.isNullOrBlank()) { moshi.adapter(Theme::class.java).fromJson(jsonTheme)?.let { return@mutableLazy it } } return@mutableLazy PREFERRED_THEME } ... } 

I’m reaching out for insights on two aspects:

  1. Design Review: Is the implementation of MutableLazy, particularly the use of double-checked locking for ensuring thread safety, correctly designed? Are there any potential pitfalls or improvements that could be suggested?

  1. Companion Object Necessity: The UNINITIALIZED value is encapsulated within a companion object to signify its unique state. However, given that UNINITIALIZED is already a singleton, is there a strong justification for using a companion object? Could it be omitted, or is there a better practice for handling such a scenario?

I appreciate any feedback or alternative approaches that could enhance this implementation. Thank you!

Thank you.

submitted by /u/yccheok
[link] [comments]

Continue ReadingFeedback Request: Implementing a mutableLazy Delegate in Kotlin for Thread-Safe Mutable Properties

Feedback Request: Implementing a mutableLazy Delegate in Kotlin for Thread-Safe Mutable Properties

I’ve been exploring Kotlin’s lazy functionality and realized it’s primarily designed for immutable variables. However, I needed a similar mechanism for mutable properties. As a result, I devised a mutableLazy delegate pattern that aims to support mutability while preserving thread safety through double-checked locking. Here’s the implementation:

 import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty fun <T> mutableLazy(initializer: () -> T): MutableLazy<T> { return MutableLazy(initializer) } class MutableLazy<T>(initializer: () -> T) : ReadWriteProperty<Any?, T> { companion object { private object UNINITIALIZED } u/Volatile private var value: Any? = UNINITIALIZED private var initializer: (() -> T)? = initializer private val lock = Any() override fun getValue(thisRef: Any?, property: KProperty<*>): T { val _v1 = value if (_v1 != UNINITIALIZED) { u/Suppress("UNCHECKED_CAST") return _v1 as T } return synchronized(lock) { val _v2 = value if (_v2 != UNINITIALIZED) { u/Suppress("UNCHECKED_CAST") _v2 as T } else { val typedValue = initializer!!() value = typedValue initializer = null // Clear the initializer to allow garbage collection of the lambda typedValue } } } override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { synchronized(lock) { this.value = value } } } 

Usage example:

 object XXXOptions { private const val THEME = "THEME" val theme: Theme by mutableLazy { val sharedPreferences = XXXApplication.instance.getSharedPreferences() val moshi = Moshi.Builder().build() val jsonTheme = sharedPreferences.getString(THEME, null) if (!jsonTheme.isNullOrBlank()) { moshi.adapter(Theme::class.java).fromJson(jsonTheme)?.let { return@mutableLazy it } } return@mutableLazy PREFERRED_THEME } ... } 

I’m reaching out for insights on two aspects:

  1. Design Review: Is the implementation of MutableLazy, particularly the use of double-checked locking for ensuring thread safety, correctly designed? Are there any potential pitfalls or improvements that could be suggested?

  1. Companion Object Necessity: The UNINITIALIZED value is encapsulated within a companion object to signify its unique state. However, given that UNINITIALIZED is already a singleton, is there a strong justification for using a companion object? Could it be omitted, or is there a better practice for handling such a scenario?

I appreciate any feedback or alternative approaches that could enhance this implementation. Thank you!

Thank you.

submitted by /u/yccheok
[link] [comments]

Continue ReadingFeedback Request: Implementing a mutableLazy Delegate in Kotlin for Thread-Safe Mutable Properties

MutableList.indexOf() is not working correctly in Kotlin scratch file

Try to run this code in Kotlin scratch.kts file:

val mutableList = mutableListOf<Int>() mutableList.add(1) mutableList.add(2) mutableList.add(3) val index = mutableList.indexOf(2) println(index) 

It will print -1. If you run it in regular Kotlin file you will get 1

Where can I report this bug to JetBrains?

submitted by /u/Ram_Fold
[link] [comments]

Continue ReadingMutableList.indexOf() is not working correctly in Kotlin scratch file

Getting creative with jqwik generators – Advanced property-based testing in Kotlin

I had a lot of fun using jqwik (https://jqwik.net/) for property-based testing of our 10 pin bowling simulator last week, and it found a bug, albeit a minor one in the construction of new games.

This week we’ll look at checking properties of games that are in play. This starts simply enough, but we soon run into the problem that because there are two balls per turn, we can’t represent a game as just random pinCounts – if we knock down 8 pins with our first ball we can’t knock down 3 with our second.

In the end I have to introduce a data model for testing which is separate from, and quite different to, our production interface. By the end I’m left wondering whether this is just an artifact for testing, or whether it is a better model overall.

In this episode

00:00:55 Review our current tested properties 00:02:02 What about properties for playing a game? 00:02:18 Strikes and spares are complicated, so let’s avoid them for now 00:03:51 We fold pinCounts into a game to play it 00:05:37 We can also write a property for scoring small pinCounts 00:07:04 Ah, but we need to actually assert something to have a property 00:07:36 Tidy the tests 00:10:03 Properties take some time to verify, can we combine them? 00:10:50 Yes if we use assertions rather than returning boolean 00:12:47 Check in 00:12:57 How can we generate spares and strikes? 00:14:46 Introduce a Turn to represent valid, erm, turns 00:17:00 We can combine providers to give another provider 00:18:10 but we have to keep the turn invariants when we do 00:19:41 Now add an operation for applying a Turn to a Game 00:22:05 jqwik finds where our logic is wrong 00:22:50 We need to make sure final turns are valid too 00:23:25 Do the simple thing first 00:24:28 Sanity check what is being generated with old fashioned println again 00:25:10 Now address bonus balls in the final frame 00:26:30 Here’s a when I prepared earlier 00:29:25 Now we need to be able to treat ValidTurn and ValidFinalTurn the same way 00:30:59 Interesting failure of type inference 00:32:01 There’s no point in trying to fight the compiler 00:33:01 Oo, a rendering bug 00:33:26 We can now test a game with more than one player 00:35:58 Commit 00:36:06 Review

You can see the code on GitHub https://github.com/dmcg/bowling-for-youtube and this miniseries in a playlist https://www.youtube.com/playlist?list=PL1ssMPpyqocjSQbAigPgMpDzLMxMc7kSv

If you like this, you’ll probably like my book Java to Kotlin, A Refactoring Guidebook (http://java-to-kotlin.dev). It’s about far more than just the syntax differences between the languages – it shows how to upgrade your thinking to a more functional style.

submitted by /u/dmcg
[link] [comments]

Continue ReadingGetting creative with jqwik generators – Advanced property-based testing in Kotlin

End of content

No more pages to load