rook
01/15/2021, 4:39 PMAlexis Cala Martínez
01/20/2021, 5:57 AMMark
01/29/2021, 2:37 AMString
once for each pattern?
fun String.romanizeAccentedChars(): String {
if (isBlank()) {
return this
}
return this
.replaceByRegex("[áàâ]", "a")
.replaceByRegex("[äæ]", "ae")
.replaceByRegex("[éèêëę]", "e")
.replaceByRegex("[íîï]", "i")
.replaceByRegex("[óōô]", "o")
.replaceByRegex("[öø]", "oe")
.replaceByRegex("[ūúùû]", "u")
.replaceByRegex("[ü]", "ue")
.replaceByRegex("[çć]", "c")
.replaceByRegex("[ß]", "ss")
}
fun String.replaceByRegex(regexStr: String, replacement: String) =
replace(regexStr.toRegex(), replacement)
SomeCat
02/05/2021, 3:09 PMhho
02/09/2021, 7:32 PMval serials = devices.map { it.motor.serial }
2️⃣:
val serials = devices.map(Device::motor).map(Motor::serial)
Is there any reason ever to go with 2️⃣?KV
02/26/2021, 2:00 PMByron Katz
02/28/2021, 3:09 AMMark
03/01/2021, 2:41 PMval resultOrNull = firstAttemptOrNull() ?: run {
if (someConditionMet()) {
secondAttemptOrNull()
} else {
null
}
}
therealbluepandabear
03/02/2021, 5:20 AMfun main() {
val capitalsService: CapitalsService = CapitalsServiceImpl(CapitalsRepositoryImpl())
capitalsService.getCapitals()
}
interface CapitalsService {
fun getCapitals(): List<Capital>
}
class CapitalsServiceImpl(private val capitalsRepository: CapitalsRepository) : CapitalsService {
override fun getCapitals(): List<Capital> = capitalsRepository.getCapitals()
}
interface CapitalsRepository {
fun getCapitals(): List<Capital>
}
class CapitalsRepositoryImpl : CapitalsRepository {
override fun getCapitals() = listOf(Capital("Paris", Country("France", "Europe", 67399000), 2175601))
}
data class Country(val countryName: String?, val continent: String?, val population: Int?)
data class Capital(val cityName: String?, val capitalOf: Country?, val population: Int?)
christophsturm
03/05/2021, 4:24 PMimport kotlin.reflect.KClass
class Creator<T:Any>(val clazz: KClass<T>) {
fun create(entity: T) {}
}
data class Post(val name:String)
class Transaction
inline fun <reified T:Any>Transaction.getCreator(): Creator<T> = Creator(T::class)
// this works:
Transaction().getCreator<Post>().create(Post("name"))
// this does not:
Transaction().getCreator().create(Post("name"))
therealbluepandabear
03/09/2021, 3:10 AMfun getValue(value: Value, param: MutableMap<Char, Int>): Pair<Char, Int> {
return when (value) {
Value.MIN -> Pair(param.keys.elementAt(param.values.indexOf(param.values.minOrNull() ?: 0)), param.values.minOrNull() ?: 0)
Value.MAX -> Pair(param.keys.elementAt(param.values.indexOf(param.values.maxOrNull() ?: 0)), param.values.maxOrNull() ?: 0)
}
}
Thanks, Tomtherealbluepandabear
03/09/2021, 4:33 AMfun getLongestStringFromList(list: List<String>): String {
val sizesDict = mutableMapOf<String, Int>()
for (string in list) {
sizesDict[string] = string.length
}
val max = sizesDict.values.indexOf(sizesDict.values.maxOrNull())
return sizesDict.keys.elementAt(max)
}
therealbluepandabear
03/09/2021, 4:33 AMchristophsturm
03/10/2021, 1:44 PMinternal data class EntityInfo<T:Any>(val idHandler: IDHandler, val classInfo: ClassInfo<T>) {
constructor(kClass: KClass<T>) : this(Table(kClass), IDHandler(kClass), ClassInfo(kClass, IDHandler(kClass)))
}
christophsturm
03/11/2021, 9:29 AMdata class Recipe(val id: Long?, val name: String, val description: String?) {
companion object {
fun find(field: KProperty1<Recipe, *>) {}
}
}
this works:
Recipe.find(field = Recipe::id)
and this is red:
Recipe.find(field = ::id)
Mark
03/12/2021, 3:37 AMrawItem
should not be exposed (and I would rather pass around LazyItems
than LazyItems<Foo>
). In other words, I want a kind of private R
generic.
class LazyItems private constructor(
private val rawItems: List<Any>,
private val processItem: (Any) -> Item,
) {
fun consumeItem(): Item {
val rawItemToConsume = someFun(rawItems) // Any
return processItem(rawItemToConsume)
}
companion object {
operator fun <R: Any> invoke(
rawItems: List<R>,
processItem: (R) -> Item
) = LazyItems(rawItems) {
processItem(it as R)
}
}
}
It’s a shame you can’t do something like:
class LazyItems constructor <R : Any> (
private val rawItems: List<R>,
private val processItem: (R) -> Item,
) {
christophsturm
03/14/2021, 10:49 PMfun mf(method: suspend () -> String) {
}
fun mf(method: suspend (String) -> String) {
}
and i can call the method that takes one parameter just fine:
mf({string->"string"})
but how can i call the other method?
mf({"string"}) // fails with overload resolution ambiguity
therealbluepandabear
03/18/2021, 4:15 AMimport biomes.Biome
import biomes.OakForest
import biomes.Savannah
import kotlin.random.Random
class World {
private var worldSize: Int = 0
private var biomes: MutableMap<IntRange, Biome> = mutableMapOf()
data class PointData(val currentPoint: Int?, val currentBiome: Biome?)
fun getPointData(point: Int): PointData {
biomes.keys.forEach {
if (it.contains(point)) {
return PointData(point, biomes[it])
}
}
return PointData(null, null)
}
companion object {
fun generateWorld(): World {
val it = World()
it.worldSize = (Random.nextInt(100000, 1000000))
var blocksCovered = 0
var priorBiomeEndPoint = 0
while (blocksCovered <= it.worldSize) {
val possibleBiomes: List<Biome> = listOf(OakForest(), Savannah())
val rand: Biome = possibleBiomes[Random.nextInt(0, 2)]
val size = blocksCovered + rand.biomeSize
it.biomes[priorBiomeEndPoint..size] = rand
priorBiomeEndPoint = blocksCovered + rand.biomeSize
blocksCovered += rand.biomeSize
}
return it
}
}
}
It will return at particular Int Ranges a certain biome:christophsturm
03/18/2021, 9:56 AMfun method() {}
fun method(number: Int, name: String) {}
// this works
val m: ()->Unit = ::method
val m2: (Int, String)->Unit = ::method
interface IImpl {
fun method()
fun method(number: Int, name: String)
}
// this does not work
val m: ()->Unit = IImpl::method
val m2: (Int, String)->Unit = IImpl::method
therealbluepandabear
03/26/2021, 3:27 AMprivate lateinit var trueButton: Button
private lateinit var falseButton: Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
trueButton = findViewById(R.id.true_button)
falseButton = findViewById(R.id.false_button)
trueButton.setOnClickListener { makeSnackbar(R.string.correct_toast, it, themeConfig = RandomSnackbarConfiguration()) }
falseButton.setOnClickListener { makeSnackbar(R.string.incorrect_toast, it, themeConfig = RandomSnackbarConfiguration()) }
}
fun makeSnackbar(resId: Int,
viewContext: View,
themeConfig: SnackbarThemeConfiguration = DefaultSnackbarConfiguration()) =
Snackbar.make(viewContext, resId, Snackbar.LENGTH_SHORT)
.setBackgroundTint(themeConfig.backgroundColor)
.setTextColor(themeConfig.textColor).let {
it.setAnimationMode(BaseTransientBottomBar.ANIMATION_MODE_SLIDE)
it.show()
}
abstract class SnackbarThemeConfiguration(val backgroundColor: Int, val textColor: Int)
class DefaultSnackbarConfiguration() : SnackbarThemeConfiguration(Color.DKGRAY, Color.WHITE)
class RandomSnackbarConfiguration() : SnackbarThemeConfiguration(
Color.rgb(Random.nextInt(0,256),
Random.nextInt(0, 256),
Random.nextInt(0, 256)),
Color.rgb(Random.nextInt(0,256),
Random.nextInt(0, 256),
Random.nextInt(0, 256)))
}
LastExceed
03/28/2021, 12:45 PMchristophsturm
03/31/2021, 2:24 PMusers = listOf("klaus", "sepperl")+if (addChris) listOf("chris") else listOf()
Marcello Galhardo
04/06/2021, 4:30 PMtherealbluepandabear
04/08/2021, 4:45 AMclass VibratorHelper {
companion object {
private val vibrationNotSupportedMessage: String = "Your device (${Build.MANUFACTURER + Build.MODEL} API ${Build.VERSION.SDK_INT}) does not support vibration."
fun vibrateFor(milliseconds: Long, context: Context) {
val service = context.getSystemService(VIBRATOR_SERVICE) as Vibrator
@Suppress("DEPRECATION")
if (!service.hasVibrator()) Toast.makeText(context, vibrationNotSupportedMessage, Toast.LENGTH_SHORT) else service.vibrate(milliseconds)
}
fun vibrateIndefinitely(context: Context) = vibrateFor(Long.MAX_VALUE, context)
}
}
Slackbot
04/09/2021, 5:38 AMZach Klippenstein (he/him) [MOD]
04/23/2021, 2:30 PMchristophsturm
04/28/2021, 3:50 PM@DslMarker
annotation class MyDSL
@MyDSL
interface RootOnly {
fun rootOnly()
}
interface RootAndLeaf : RootOnly {
fun call(function: Leaf.() -> Unit)
fun rootAndLeaf()
}
@MyDSL
interface Leaf {
fun leaf()
}
val block: RootAndLeaf.() -> Unit = {
call {
leaf()
rootAndLeaf() // cannot be called by implicit receiver
}
}
Mark
05/03/2021, 7:00 AMLazy
is to encourage the result of suspendableLazy()
to be used as a property (since it doesn’t make sense to use it otherwise):
interface SuspendableLazy<T>: Lazy<suspend () -> T>
fun <T> suspendableLazy(scope: CoroutineScope, provider: suspend () -> T) = object : SuspendableLazy<T> {
private val computed = scope.async(start = CoroutineStart.LAZY) { provider() }
override val value: suspend () -> T
get() = computed::await
override fun isInitialized() = computed.isCompleted
}
fun <T> suspendableLazy(provider: suspend () -> T) = object : SuspendableLazy<T> {
@Volatile // since we are using the double-checked pattern
private var computedLambda: (suspend () -> T)? = null
private val mutex = Mutex()
override val value: suspend () -> T
get() {
computedLambda?.also {
return it
}
return result@{
// because now we are inside the lambda being returned
computedLambda?.also {
return@result it()
}
mutex.withLock {
// because now we have the lock
computedLambda?.also {
return@withLock it()
}
provider().also { computedValue ->
computedLambda = { computedValue }
}
}
}
}
override fun isInitialized() = computedLambda != null
}
// usage
val fooDelegate by suspendableLazy { /* compute Foo */ }
suspend fun fooValue(): Foo = fooDelegate()
elect
05/09/2021, 5:52 AMvar c = it.read() // it: InputStream
while (c != -1) {
..
c = it.read()
}
Haris Khan
05/11/2021, 2:51 AMinline fun <reified T : Any> MongoCollection<T>.replaceOne(
replacement: T,
options: ReplaceOptions = ReplaceOptions()
): UpdateResult = replaceOneById(KMongoUtil.extractId(replacement, T::class), replacement, options)
I want to create a wrapper around it like so :
inline fun <reified T : Any> insertOrReplaceOne(document: T) {
collection.replaceOneById
}
Collection is of type MongoCollection<T> ... but the extension function fails to be applicable for some reason (this is a function in a parameterized class if it matters (same type T)) aka
abstract class BaseMongoPlatformRepository<T : Any> { }
Haris Khan
05/11/2021, 2:51 AMinline fun <reified T : Any> MongoCollection<T>.replaceOne(
replacement: T,
options: ReplaceOptions = ReplaceOptions()
): UpdateResult = replaceOneById(KMongoUtil.extractId(replacement, T::class), replacement, options)
I want to create a wrapper around it like so :
inline fun <reified T : Any> insertOrReplaceOne(document: T) {
collection.replaceOneById
}
Collection is of type MongoCollection<T> ... but the extension function fails to be applicable for some reason (this is a function in a parameterized class if it matters (same type T)) aka
abstract class BaseMongoPlatformRepository<T : Any> { }