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
getting-started
  • m

    Marko Novakovic

    12/22/2021, 1:30 PM
    since I updated Kotlin to 1.6.10 and coroutines to 1.6.0,
    kotlin-test
    broke 🤔 can’t fine
    import kotlin.test.Test
    annotation. is there something going on with kotlin test that am not aware of?
    s
    • 2
    • 5
  • m

    Marko Novakovic

    12/22/2021, 3:23 PM
    something am thinking about lately. would you use factory methods on a class, for example
    create()
    , method that is explicitly named or use
    invoke
    operator function on a
    companion object
    ?
    v
    a
    d
    • 4
    • 13
  • l

    leysont

    12/22/2021, 4:39 PM
    Is this the right place to ask something about Jetbrain's Compose for desktop? I just started using it and columns seem to be scrollable always and even scroll away components that are not in the column. If the column is is another column or in a box then sibling composables above and below it also scroll. Is this normal behavior?
    y
    r
    • 3
    • 7
  • a

    Ankit Shah

    12/22/2021, 5:15 PM
    Hello everyone, just a small question. In kotlin lets say I do, 
    (10/3).toInt()
     it returns 3 but what I want is the upper value i.e. 4. How can I achieve it?
    i
    r
    +3
    • 6
    • 7
  • f

    Filipe Duarte

    12/23/2021, 5:58 PM
    I updated kotlin and IntelliJ, and when I tried to execute a specific .kt file that contained the main function, it was impossible because it says that I was trying to overload the main function. I always used main functions alongside specific kotlin files in the same project. Maybe it was the Gradle.. I don’t know what to do
    e
    • 2
    • 2
  • j

    Josh Horwitz

    12/24/2021, 1:44 AM
    Hey all! Quick question, what is the best up to date book as far as learning kotlin as an experienced dev currently?
    m
    k
    • 3
    • 4
  • g

    Glen

    12/24/2021, 1:46 PM
    Hello here. I have updated my Kotlin to 1.6.0 and when compiling some Kotlin code I get a warning and I don't know how to solve it.
    a
    p
    a
    • 4
    • 9
  • c

    Chetan Tuteja

    12/27/2021, 7:19 AM
    Hi guys! Quick question. Let us say I have a string array and I have another variable and I am just checking if that variable is in the array. I can directly use the
    in
    check for that. Is there any way to do the same check while ignoring case check? I know I can do the
    any
    check, anything besides that?
    val abc = "abc"
    val random = arrayOf("ABC", "egf")
    
    val isThere = abc in random // Prints false
    e
    i
    +4
    • 7
    • 16
  • m

    Mendess

    12/27/2021, 1:07 PM
    where is the documentation on what characters are allowed in a function name with backticks? I can't find any
    v
    • 2
    • 1
  • g

    Grian

    12/28/2021, 5:55 AM
    Does anyone know if it's possible to create a DSL like this:
    myDsl { 
        1,
        2,
        3,
    }
    and end up with like a list of
    1, 2, 3
    somewhere in the DSL's code
    🇳🇴 2
    j
    r
    • 3
    • 2
  • a

    asavio

    12/28/2021, 8:59 AM
    Hey guys, Does anyone know a mechanism to sort a possibly infinite
    Sequence
    or one with a really a large count of objects lazily without it being too time consuming like the factory methods?
    r
    e
    • 3
    • 9
  • h

    hfhbd

    12/28/2021, 4:05 PM
    How can you check, if a class has an initializer for a lateinit variable, when this class is passed as variable to another class?
    class Config {
        lateinit var s: String
    }
    class Consumer(val config: Config) {
        init {
             require(config::s.isInitialized)
        }
    }
    My current workaround is using an internal member function:
    fun isInitialized() = ::s.isInitialized
    and call this function in
    require
    .
    a
    m
    • 3
    • 3
  • j

    JonasDaWi

    12/28/2021, 5:07 PM
    Does anyone know how I can make a httpmethod=SEARCH request in ktor? In curl it works like this: curl host -X SEARCH
    v
    k
    • 3
    • 4
  • e

    Eivind

    12/29/2021, 9:03 AM
    Hi, I have a data class named
    Error
    that I want to use to represents errors occuring in my api (not exceptions, but state different than what the user expected when they made their request). When I use it now Kotlin defaults to the java.lang.Error. Can I change this default, or should I pick a different name?
    m
    m
    t
    • 4
    • 12
  • d

    David W

    12/29/2021, 8:38 PM
    I have an inline function that takes a
    List<Lock>
    and an anonymous function. It needs to lock all of the locks, execute the function, and then unlock all locks. The anonymous function should also allow non-local returns. I've been banging my head against this for hours, anyone have a solution?
    inline fun <T> write(locks: List<ReentrantReadWriteLock>, action: () -> T): T
    j
    e
    n
    • 4
    • 25
  • m

    mcpiroman

    12/31/2021, 3:18 PM
    I have the following pattern:
    abstract class Base<T : Any>(val clazz: KClass<T>)
    
    class Foo; class Bar;
    object A : Base<Foo>(Foo::class) { ... }
    object B : Base<Bar>(Bar::class) { ... }
    Can I somehow 'reifine' the `T`paramater so I only have to write the parameter class once, e.g. `Base<Foo>()`or
    Base(Foo::class)
    ? Edit: OK, it's fine that it's possible but I actually meant to ask 'how' to do that. The 2 ways I suggested above do not compile, nor can I use `reified`modifier.
    :yes: 2
    k
    t
    • 3
    • 3
  • m

    MisileLab

    01/01/2022, 7:48 AM
    How change sequence element?
    r
    m
    • 3
    • 2
  • j

    James Whitehead

    01/01/2022, 7:36 PM
    Hi 👋 • What is the correct way to write a function signature using generics, whereby the first parameter is something like 
    <T>
     and the second parameter is "an instance or implementation of T"? • Also kind of related question: When should one use
    <T>
    vs
    <T : Any>
    , I'm not really sure what the difference is? Thanks in advance 🙂
    j
    j
    m
    • 4
    • 9
  • a

    Ayfri

    01/02/2022, 5:11 AM
    Hi ! Is there any way to force Tree Shaking in Kotlin/JVM ? I have this really simple code
    private inline fun execute(block: () -> Unit) = block()
    
    fun main() {
    	execute { println("test") }
    }
    But when I see the Bytecode, it creates an
    execute
    static method on the MainKt class but never use it, is there a way to say to the compiler to not generate this method and just inline ?
    e
    h
    +2
    • 5
    • 18
  • h

    hfhbd

    01/02/2022, 10:54 AM
    If you write a library and want to provide 1! useful test function, where do you store this function? In the main source with a comment, in the main source with an extra annotation like
    TestingOnly
    , or do you really create a new module containing only 1 function and publish it?
    r
    • 2
    • 1
  • r

    Rob Elliot

    01/02/2022, 11:42 AM
    Any recommendations for a library that can do string escaping, other than
    org.apache.commons.text.StringEscapeUtils
    ?
    j
    e
    • 3
    • 15
  • p

    Pablo

    01/02/2022, 12:59 PM
    How can I create a Map (it that's the best way) of having something for instance : 400 to CustomExceptionFor400 500 to CustomExceptionFor500 The first param is an Int and it's a HttpStatusCode, and the value is something like this
    sealed class OrganizationExceptions : Exception() {
        object OrganizationNotFound : OrganizationExceptions()
        object ListNotAvailable : OrganizationExceptions()
    }
    This is an example, but it won't be always "OrganizationExceptions" I'm creating a method generic, also I don't know if it's better to create a sealed class or create
    class OrganizationNotFoundException : Throwable() //or Exception()
    class ListNotAvailable : Throwable() //or Exception()
    Any recomendations? the method signature is :
    fun apiCallWithStatusCode(codes : HashMap<Int, Throwable>, apiCall : suspend () -> Response<T>,){...}
    a
    j
    m
    • 4
    • 9
  • s

    sorianog

    01/03/2022, 2:50 PM
    I’m reviewing my Leetcode Java submissions and thought, I’d see what the code would look like with the Automagic to Kotlin conversion from Studio. One problem that I solved with updated Kotlin code seems to be less performant (by Leetcode benchmarking) 🤔 Maybe I’m not hitting their servers at the right time 😛 https://leetcode.com/problems/move-zeroes/discuss/1664500/Java-to-Kotlin-Converted-Solution%3A-Less-Performant-with-Kotlin
    j
    e
    • 3
    • 6
  • g

    glenkpeterson

    01/03/2022, 10:43 PM
    Why isn't my JVM Double variable the same as itself in 1.6.10?
    val dotOne: Double = "0.1".toDouble()
            assertSame(dotOne, dotOne)
    
    expected: java.lang.Double@76774d21<0.1> but was: java.lang.Double@68be905c<0.1>
    I understand that
    assertSame
    uses referential equality (checks that the parameters have the same virtual memory address) and should function like the
    ===
    operator.
    0.1 !== 0.1
    because they are primitives and could be boxed to different objects before being compared for referential equality. But, when I declare a variable, I would expect it to have the same virtual memory address as itself. Be referentially (and structurally) equivalent to itself. Can I declare my variable somehow to not be compiled away to two different primitives that happen to have different virtual memory addresses?
    e
    v
    • 3
    • 6
  • d

    dave08

    01/04/2022, 12:20 PM
    Will using this (with the `as`s, componentX and type params) get the array boxed?
    @JvmInline
    value class MethodParams1<A1>(val value: Array<Any?>) {
      
        operator fun component1() = value[0] as A1
        var arg1: A1
            get() = value[0] as A1
            set(value) { this.value[0] = value }
    }
    j
    e
    • 3
    • 24
  • c

    Colton Idle

    01/05/2022, 5:10 AM
    I wrote two extension functions that take different Types in the List type generic, but I get an error saying that I can't do that
    private fun List<NetworkFoo>.mapToDomain(): List<DomainFoo> {
      return this.map { //stuff }
    }
    and
    private fun List<NetworkBar>.mapToDomain(): List<DomainBar> {
      return this.map { //stuff }
    }
    Error
    Platform declaration clash: The following declarations have the same JVM signature
    I suppose the error message is helpful in giving me a hint that these two methods are identical in JVM land? If I use the auto-correct option I get
    @JvmName("mapToDomaincom.network.model.NetworkBar")
    but the annotation gives me an error of:
    Illegal JVM name
    e
    s
    r
    • 4
    • 6
  • s

    Simon Lin

    01/05/2022, 6:58 AM
    How can I add element in specified index and if the index exist element, replace it.
    val list = mutableListOf<String>()
    
    list.add(0, "a")
    list.add(0, "b")
    
    list.toString() // except [b], actual [b, a]
    g
    • 2
    • 12
  • j

    Jason5lee

    01/05/2022, 12:25 PM
    I’m building a string with some logics, like
    "something${somelogic}something${somelogic}"
    . But it ends up being too long for a line. Any tips to rewrite to make the line shorter but still being conscious of how the string is built?
    i
    k
    r
    • 4
    • 5
  • j

    Jasin Colegrove

    01/05/2022, 12:39 PM
    Does anyone have any advice on printing documents from a kotlin desktop app? I need to be able to create printable documents from database data. I've looked at PDFBox (create PDF's that can later be printed) but I really want a clean idiomatic kotlin way of doing it?
    i
    r
    • 3
    • 7
  • l

    Liudvikas Sablauskas

    01/05/2022, 1:10 PM
    Hello everyone. This is not really a question for #getting-started, but I couldn't find a better place (if there is, tell me). 3 years ago I held an internal company contest with 7 Kotlin edge case / oddity puzzles. Today we decided to revisit and solve them. We solved all except one. Can someone help us crack this nut?
    /**
     * Task: Make line `DisNonNullable.nonNull()` not compile
     * Clarification: `DisNonNullable.nonNull()` will always have a non-null value, so it makes sense to not allow that method
     * Clarification: Everything else has to compile just as before, only `DisNonNullable.nonNull()` should fail
     * Clarification: The non-generic parameter type String is chosen only as an example. This hardcoded type is not the focus of the task
     * Restrictions: Mustn't modify main() method, DisNullable and DisNotNullable classes
     */
    
    fun main(args: Array<String>) {
        DisNullable.nonNull()
        DisNonNullable.nonNull()
    }
    
    abstract class GenericMapper<T>  {
        abstract fun map(string: String): T
    
        fun nonNull(): GenericMapper<T> {
            val delegate = this
            return object : GenericMapper<T>() {
                override fun map(string: String): T {
                    return delegate.map(string)
                }
            }
        }
    }
    
    object DisNullable : GenericMapper<String?>() {
        override fun map(string: String) = string
    }
    
    object DisNonNullable : GenericMapper<String>() {
        override fun map(string: String) = string
    }
    r
    j
    • 3
    • 19
Powered by Linen
Title
l

Liudvikas Sablauskas

01/05/2022, 1:10 PM
Hello everyone. This is not really a question for #getting-started, but I couldn't find a better place (if there is, tell me). 3 years ago I held an internal company contest with 7 Kotlin edge case / oddity puzzles. Today we decided to revisit and solve them. We solved all except one. Can someone help us crack this nut?
/**
 * Task: Make line `DisNonNullable.nonNull()` not compile
 * Clarification: `DisNonNullable.nonNull()` will always have a non-null value, so it makes sense to not allow that method
 * Clarification: Everything else has to compile just as before, only `DisNonNullable.nonNull()` should fail
 * Clarification: The non-generic parameter type String is chosen only as an example. This hardcoded type is not the focus of the task
 * Restrictions: Mustn't modify main() method, DisNullable and DisNotNullable classes
 */

fun main(args: Array<String>) {
    DisNullable.nonNull()
    DisNonNullable.nonNull()
}

abstract class GenericMapper<T>  {
    abstract fun map(string: String): T

    fun nonNull(): GenericMapper<T> {
        val delegate = this
        return object : GenericMapper<T>() {
            override fun map(string: String): T {
                return delegate.map(string)
            }
        }
    }
}

object DisNullable : GenericMapper<String?>() {
    override fun map(string: String) = string
}

object DisNonNullable : GenericMapper<String>() {
    override fun map(string: String) = string
}
r

Rob Elliot

01/05/2022, 1:23 PM
It breaks the rules, but this is what I'd do:
fun main(args: Array<String>) {
  DisNullable.nonNull()
  DisNonNullable.nonNull()
}

// Internal so that there are only two immediate subtypes, but it isn't sealed, so other subtypes of
// those immediate subtypes can be defined in other packages.
abstract class GenericMapper<T> internal constructor() {
  abstract fun map(string: String): T
}

abstract class NullableGenericMapper<T> : GenericMapper<T>()  {

  fun nonNull(): GenericMapper<T> {
    val delegate = this
    return object : GenericMapper<T>() {
      override fun map(string: String): T {
        return delegate.map(string)
      }
    }
  }
}

abstract class NonNullableGenericMapper<T : Any> : GenericMapper<T>()

object DisNullable : NullableGenericMapper<String?>() {
  override fun map(string: String) = string
}

object DisNonNullable : NonNullableGenericMapper<String>() {
  override fun map(string: String) = string
}
Hang on - don't think I understood the purpose of
fun nonNull()
when I wrote that. Guess in my version it should return
NonNullableGenericMapper
.
l

Liudvikas Sablauskas

01/05/2022, 1:39 PM
It's incorrect, DisNullable and DisNonNullable should extend the same class
But I definitely remember that there was a solution, exactly according to these rules
r

Rob Elliot

01/05/2022, 1:41 PM
They do. Just with an extra layer of inheritance in the middle.
l

Liudvikas Sablauskas

01/05/2022, 1:42 PM
And that is not allowed 😄
object DisNullable : GenericMapper<String?>() {
    override fun map(string: String) = string
}

object DisNonNullable : GenericMapper<String>() {
    override fun map(string: String) = string
}
This should not change at all
r

Rob Elliot

01/05/2022, 1:42 PM
Why?
l

Liudvikas Sablauskas

01/05/2022, 1:43 PM
This is a puzzle, of course in practice you wouldn't care either way 😄
r

Rob Elliot

01/05/2022, 1:44 PM
But even puzzles need to justify their requirements.
Particularly if they are puzzles without a known solution. It's one thing to say "The constraints may seem arbitrary, but they can be met" as an intellectual challenge. "The constraints are arbitrary and it may be impossible to meet them" is silly - why would anyone waste their time trying to meet arbitrary constraints that are impossible to meet?
l

Liudvikas Sablauskas

01/05/2022, 1:46 PM
"The constraints are arbitrary and it may be impossible to meet them
No, I just said that
But I definitely remember that there was a solution, exactly according to these rules
r

Rob Elliot

01/05/2022, 1:47 PM
Ah, missed that in the middle of the thread. Fair enough.
👍 2
FWIW though on the illegal version it is possible to constrain the nullable type to a non-nullable one:
abstract class NullableGenericMapper<E : Any> : GenericMapper<E?>() {
  fun nonNull(): NonNullableGenericMapper<E> = TODO()
}

object DisNullable : NullableGenericMapper<String>() {
  override fun map(string: String): String? = null
}
j

Jason5lee

01/05/2022, 2:34 PM
Clarification: `DisNonNullable.nonNull()` will always have a non-null value, so it makes sense to not allow that method
It does not make sense to me.
r

Rob Elliot

01/05/2022, 2:46 PM
I think the intention of
nonNull
is to transform a
GenericMapper<String?>
into a
GenericMapper<String>
so that when you call
map
on it you get back a
String
not a
String?
. So calling
GenericMapper<String>.nonNull()
is pointless - it would effectively return itself - and the idea is to make it not compile so that people don't accidentally call it.
l

Liudvikas Sablauskas

01/05/2022, 2:49 PM
Yes, you are correct, that's the reason
r

Rob Elliot

01/05/2022, 3:07 PM
It's trivial of course once you remember the existence of extension functions:
fun main(args: Array<String>) {
  DisNullable.nonNull()
  DisNonNullable.nonNull()
}

abstract class GenericMapper<T>  {
  abstract fun map(string: String): T
}

fun <T> GenericMapper<T?>.nonNull(): GenericMapper<T> {
  val delegate = this
  return object : GenericMapper<T>() {
    override fun map(string: String): T {
      return delegate.map(string) ?: TODO("handle null")
    }
  }
}

object DisNullable : GenericMapper<String?>() {
  override fun map(string: String) = string
}

object DisNonNullable : GenericMapper<String>() {
  override fun map(string: String) = string
}
❤️ 1
l

Liudvikas Sablauskas

01/05/2022, 3:25 PM
Wow, that's a nice solution and it's definitely valid! Though I still can't remember if that's also the solution that I used 3 years ago, but it very well might be. Thanks!
View count: 1