https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
codereview
  • r

    rook

    01/15/2021, 4:39 PM
    Hello, I made this a few weeks ago and I just wanted to get some feedback on the implementation and maybe on the usefulness/syntax/design of its use?
    BundleDelegate.kt
    j
    • 2
    • 6
  • a

    Alexis Cala Martínez

    01/20/2021, 5:57 AM
    Hello how could i do this better
    Untitled
    m
    • 2
    • 10
  • m

    Mark

    01/29/2021, 2:37 AM
    Is there a smarter way to do something like this? Presumably, not creating new regexes each time would be a start. But what about the inefficiency of parsing through the
    String
    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)
    g
    j
    • 3
    • 8
  • s

    SomeCat

    02/05/2021, 3:09 PM
    Untitled
    m
    • 2
    • 7
  • h

    hho

    02/09/2021, 7:32 PM
    1️⃣:
    val 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️⃣?
    1️⃣ 5
    j
    l
    • 3
    • 4
  • k

    KV

    02/26/2021, 2:00 PM
    what is the best way to find the common element from the character array? Suppose I have 2 character array and both arrays have some common characters. How to find those characters?
    t
    m
    j
    • 4
    • 4
  • b

    Byron Katz

    02/28/2021, 3:09 AM
    I've tried many approaches, nothing seems to work.
    t
    m
    • 3
    • 4
  • m

    Mark

    03/01/2021, 2:41 PM
    Is there a nicer way to write this:
    val resultOrNull = firstAttemptOrNull() ?: run {
        if (someConditionMet()) {
            secondAttemptOrNull()
        } else {
            null
        }
    }
    d
    j
    • 3
    • 10
  • t

    therealbluepandabear

    03/02/2021, 5:20 AM
    How is this code I did with DI. How could I improve this?
    fun 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?)
    m
    j
    d
    • 4
    • 7
  • c

    christophsturm

    03/05/2021, 4:24 PM
    is there a way to get this to work without specifying the generic type:
    import 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"))
    u
    • 2
    • 2
  • t

    therealbluepandabear

    03/09/2021, 3:10 AM
    Can this code be shortened?
    fun 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, Tom
    a
    e
    e
    • 4
    • 18
  • t

    therealbluepandabear

    03/09/2021, 4:33 AM
    How is this code for analysing the longest string in a list:
    fun 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)
    }
    m
    • 2
    • 3
  • t

    therealbluepandabear

    03/09/2021, 4:33 AM
    It seems to work fine, but could improvements be made to this?
    m
    • 2
    • 2
  • c

    christophsturm

    03/10/2021, 1:44 PM
    in this code, is there a way to avoid creating IdHandler twice?
    internal 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)))
    }
    s
    • 2
    • 3
  • c

    christophsturm

    03/11/2021, 9:29 AM
    if i have a method that takes a kproperty1 for one specific class, why does the kotlin compiler not allow to omit the class name when calling it?
    data 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)
    u
    • 2
    • 3
  • m

    Mark

    03/12/2021, 3:37 AM
    Is there a better way to define this class? Note, I don’t want to use a generic parameter, because the type of
    rawItem
    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,
    ) {
    j
    • 2
    • 2
  • c

    christophsturm

    03/14/2021, 10:49 PM
    it seems i can define 2 methods where the only difference in signature is the number of parameters that their lambda takes:
    fun 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
    s
    m
    • 3
    • 6
  • t

    therealbluepandabear

    03/18/2021, 4:15 AM
    I created a world generator for a game I'm making: Thoughts on it?
    import 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:
    l
    m
    • 3
    • 3
  • c

    christophsturm

    03/18/2021, 9:56 AM
    how do i get a method reference to an overloaded interface function?
    fun 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
    🤔 1
    d
    • 2
    • 2
  • t

    therealbluepandabear

    03/26/2021, 3:27 AM
    Code for a first app I made: (displpays a random snackbar.)
    private 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)))
    }
    e
    b
    • 3
    • 4
  • l

    LastExceed

    03/28/2021, 12:45 PM
    I'm getting into functional programming, here is my implementation of conways game of life. I feel like the content of main() doesnt really fit the functional paradigm, but i can't figure out a better way that doesn't risk stack overflow (unless I use stuff like tailrec which feels like cheating). I tried looking at other peoples implementations online, but they all seem ridiculously complicated. any advice ?
    Untitled
    e
    • 2
    • 2
  • c

    christophsturm

    03/31/2021, 2:24 PM
    is there a better way to write this? :
    users = listOf("klaus", "sepperl")+if (addChris) listOf("chris") else listOf()
    l
    z
    i
    • 4
    • 9
  • m

    Marcello Galhardo

    04/06/2021, 4:30 PM
    Hey folks, in your opinion what is more "Kotlin Idiomatic" way for guard clauses? 🤔
    2️⃣ 6
    1️⃣ 4
    e
    m
    • 3
    • 5
  • t

    therealbluepandabear

    04/08/2021, 4:45 AM
    I created this kind of 'VibratorHelper' class to help with vibration, opinions?
    class 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)
        }
    }
    e
    • 2
    • 14
  • s

    Slackbot

    04/09/2021, 5:38 AM
    This message was deleted.
    e
    t
    m
    • 4
    • 24
  • z

    Zach Klippenstein (he/him) [MOD]

    04/23/2021, 2:30 PM
    Yea, I don’t think this is just a kotlin concept, and it’s not new. A lot has been written about the dangers of using exceptions for non-exceptional errors, control flow, etc. It’s a lot easier to solve when you have a stronger type system like kotlin does. Functional programming has patterns to solve this that have become pretty popular in modern kotlin. It’s painful to try to adopt if you’re migrating an old codebase, but if you think about this when you’re initially designing and writing code it’s a lot easier.
    t
    c
    +2
    • 5
    • 15
  • c

    christophsturm

    04/28/2021, 3:50 PM
    I’m trying to use dsl marker to allow some methods only on the root , some only on the leaf, and some on both. but it seems to not work. I cannot call `rootAndLeaf`despite it being in an interface without dsl marker. maybe the dsl marker is inherited?
    @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
        }
    }
    r
    • 2
    • 1
  • m

    Mark

    05/03/2021, 7:00 AM
    Here, the purpose of implementing
    Lazy
    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()
    e
    u
    • 3
    • 23
  • e

    elect

    05/09/2021, 5:52 AM
    any better way than duplicate code like this? (I'm receive a json response in 1 line, I want to loop char by char to properly display it for debug with the right new lines and indentations)
    var c = it.read() // it: InputStream
            while (c != -1) {
                ..
                c = it.read()
            }
    e
    m
    • 3
    • 13
  • h

    Haris Khan

    05/11/2021, 2:51 AM
    There's this reified function that I'm calling... Is it possible to generically call it?
    inline 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> { }
    🇳🇴 1
    • 1
    • 1
Powered by Linen
Title
h

Haris Khan

05/11/2021, 2:51 AM
There's this reified function that I'm calling... Is it possible to generically call it?
inline 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> { }
🇳🇴 1
ah that sucks 😞 ... I was able to have my function accept a KClass and work around this limitation
View count: 4