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
  • v

    vsr

    03/16/2021, 3:54 PM
    Hey peeps, I started using Kotlin recently and while trying to build my first Gradle-based task using Ktor (https://ktor.io/docs) I realised I had to kill the running task (
    ./gradlew run
    ) after making code changes. Is there a hot module reloading concept in Kotlin (coming from a frontend background) 🙂
    t
    • 2
    • 2
  • t

    tseisel

    03/16/2021, 3:58 PM
    Given the following sealed class definition and
    Flow
    operator chain:
    sealed class LoadRequest<out T> {
      object Pending : LoadRequest<Nothing>()
      class Success<T>(val data: T) : LoadRequest<T>()
      class Failure(val error: Exception) : LoadRequest<Nothing>()
    }
    
    val someFlow: Flow<Foo> = ...
    val requestFlow: Flow<LoadRequest<Foo>> = someFlow
      .map { LoadRequest.Success(it) as LoadRequest<Foo> }
      .onStart { emit(LoadRequest.Pending) }
      .catch { emit(LoadRequest.Failure(it) }
    The
    as LoadRequest<Foo>
    part is marked as
    No cast needed
    , but if I remove it then I get
    Type mismatch
    on
    LoadRequest.Pending
    and
    LoadRequest.Failure
    (it expects a
    LoadRequest.Success<Foo>
    ). Is it a compiler bug or is there a workaround ? I'd expect the compiler to figure out the proper type by analyzing the whole operator chain.
    d
    • 2
    • 1
  • n

    Nate Emmons

    03/17/2021, 3:29 PM
    Perhaps it's just as simple as "square braces are syntactic sugar for calling the 'set' method on the given object"?
    :thread-please: 1
    c
    • 2
    • 4
  • v

    Varun

    03/19/2021, 3:11 PM
    hey really rookie question. If i have a mutable map = {3=0, 4=0, 5=0, 6=0, 7=1, 8=1, 9=1, 10=1, 11=2} . If I'm trying to get the max value in this --map.maxBy{it.value} . It returns a value 11=2. What type is this and how do I get the value "2" from it? -> https://leetcode.com/playground/eQrqK2Ug
    ✅ 1
    w
    a
    • 3
    • 7
  • v

    Varun

    03/20/2021, 4:08 AM
    hey why can't I use "removeFirst" here? https://leetcode.com/playground/EViekAXG
    j
    • 2
    • 2
  • t

    therealbluepandabear

    03/20/2021, 10:30 PM
    Can anyone recommend some good Gradle tutorials? I'm having a hard time finding good Gradle tutorials... I also want to work with the Kotlin DSL
    :google: 2
    b
    b
    • 3
    • 91
  • t

    thhh

    03/21/2021, 9:56 AM
    Hi. I am unable to see the print output for coroutines in IntelliJ Idea. For other normal kotlin code, it works fine. I have added question for details here: https://stackoverflow.com/questions/66730626/different-outputs-when-using-kotlin-playground-by-google-android-vs-intellij-w I am trying to run the code:
    import kotlinx.coroutines.*
    
    
    fun main() {
        repeat(3) {
            GlobalScope.launch {
                println("Hi from ${Thread.currentThread()}")
            }
        }
    }
    on IntelliJ idea 2020.3.2: The output is this:
    6:14:05 PM: Executing task 'Coroutines_multipleKt.main()'...
    
    > Task :wrapper
    
    BUILD SUCCESSFUL in 184ms
    1 actionable task: 1 executed
    > Task :compileKotlin
    > Task :compileJava NO-SOURCE
    > Task :processResources NO-SOURCE
    > Task :classes UP-TO-DATE
    > Task :Coroutines_multipleKt.main()
    
    BUILD SUCCESSFUL in 712ms
    2 actionable tasks: 2 executed
    6:14:06 PM: Task execution finished 'Coroutines_multipleKt.main()'.
    But on Kotlin Playground I get the output that is expected:
    Hi from Thread[DefaultDispatcher-worker-1 @coroutine#1,5,main] Hi from Thread[DefaultDispatcher-worker-1 @coroutine#2,5,main] Hi from Thread[DefaultDispatcher-worker-1 @coroutine#3,5,main]
    What am I doing wrong? Why doesn't IntelliJ produce the output as desired? I have added an image:

    https://i.imgur.com/N9WjEZz.png▾

    where IntelliJ shows output, but as you can see its not producing output. Generally the blue highlighted area is where the println output would be I have added an GIF, please check:

    https://i.imgur.com/1unP2hY.gif▾

    It shows how one code works and one does not. Please guide where its going wrong
    • 1
    • 1
  • d

    Daniele B

    03/21/2021, 1:42 PM
    I would like to define a class such as
    ScreenState
    and a function like
    emptyScreen()
    data class AppState (
        val masterState : ScreenState<MasterData> = ScreenState<MasterData>(),
        val detailState : ScreenState<DetailData> = emptyScreen(),
    )
    
    data class MasterData (
        val countriesList : List<CountriesListItem> = emptyList(),
        ...
    )
    data class DetailData (
        val countryInfo : CountryInfo = CountryInfo(),
        ...
    )
    I was trying to follow the Kotlin definitions of
    List
    and
    emptyList()
    but I got stuck it should be something similar to this?
    public interface ScreenState<screenData T> {
        val isLoading: Boolean = false,
        val screenData: T? = null,
    }
    
    public fun <T> emptyScreen(): ScreenState <T> = EmptyScreen
    
    internal object EmptyScreen : ScreenState <Nothing> {
    }
    y
    • 2
    • 4
  • d

    Daniele B

    03/21/2021, 5:35 PM
    how can I make an instance of the reified class type?
    inline fun <reified T:Any> getResponse(endpoint : String): T? {
    	
    	val newObj = T()
    	....
    
        }
    y
    • 2
    • 16
  • d

    Daniele B

    03/22/2021, 10:33 AM
    How can I do something like this?
    fun isClass(theObject : Any, theClass : KClass) : Boolean {
        if (theObject is theClass) {
            return true
        }
        return false
    }
    I would like to use it in this way:
    val verification = isClass(myObject, Person::class)
    a
    r
    k
    • 4
    • 17
  • k

    Kenneth

    03/22/2021, 1:42 PM
    What is recommended to do when you have a case in a when where you want do to noting? Just empty {}?
    m
    t
    +2
    • 5
    • 4
  • a

    allan.conda

    03/24/2021, 9:52 AM
    sealed class Error(val code: String) {
        object Type1 : Error("type1")
        data class Type2(val someParam: String) : Error("type2")
    }
    
    // somewhere else in code
    if (error.code == Type2.code) { }
    Is there a best practice for achieving a check like above with a data class sealed class?
    r
    m
    • 3
    • 14
  • d

    diego.brum

    03/24/2021, 3:30 PM
    Hello all, in C# we have Tuple class (a helper class) to make easy use destructor, for instance
    var (x, y) = Tuple.Create("hello", "world");
    // or
    var (x, y) = ("hello", "again");
    // or also
    var x = ("hello", "again");
    x.Item1 // hello
    x.Item2 // again
    // or also also
    var x = (Xpto: "Hello", Yup: "Again")
    x.Xpto 
    x.Yup
    in Kotlin I had read about destructors and find the Pair class Is it the equivalent? And is it possible initialise "Pair" on the fly like C#?
    r
    c
    j
    • 4
    • 9
  • j

    Jonathan Olsson

    03/25/2021, 7:57 AM
    Hi! I am using kotlinx.serialization and am running into some issues with regards to generic values in data classes. I have roughly the following:
    @Serializable
    data class BaseResult<T>(val data: T, val foo: Int)
    
    @Serializable
    data class SomeData(val bar: String)
    
    // Then when decoding incoming json I do:
    val response = Json { ignoreUnknownKeys = true }
        .decodeFromString<BaseResult<SomeData>>(responseBody)
    When doing this I get the following error:
    Serializer for class 'SomeData' is not found.
    kotlinx.serialization.SerializationException: Serializer for class 'SomeData' is not found.
    Mark the class as @Serializable or provide the serializer explicitly.
    a
    • 2
    • 2
  • j

    Jonathan Olsson

    03/25/2021, 11:45 AM
    What is the best approach in kotlinx.serialization to encode parameterised values, ie:
    enum class Status(val value: Int) {
      Ok(0),
      NotOk(1),
      SomeOtherStatus(2)
    }
    k
    a
    • 3
    • 5
  • j

    jbruckne

    03/25/2021, 8:24 PM
    I have a question about kotlin multiplatform, if anyone here is familiar. How does a gradle project specify which target of the multiplatform project to consume. Like if I publish both jvm and android targets, can I then specify something like
    implementation('com.example:MyKMMProject-jvm:1.0')
    ?
    w
    • 2
    • 2
  • j

    JsebasCT

    03/26/2021, 12:25 PM
    Hi there, does anyone has a sample implementation of the chain of responsibility pattern ?
    m
    • 2
    • 2
  • d

    DMITRY.

    03/30/2021, 11:21 AM
    mongoOperations.findAndModify(searchQuery, update, T::class.java)
    Cannot use 'T' as reified type parameter. Use a class instead. How make it work?
    r
    • 2
    • 14
  • d

    Dennis Tel

    03/31/2021, 5:01 PM
    Maybe a n00b question, but is there a way to treat XMLStreamReader as a Sequence? Want to process an XML feed with constant memory and use things like
    .windowed
    but not sure if this is the way to go. Pretty new to Kotlin and the JVM 😬
    n
    t
    • 3
    • 44
  • a

    Arrow

    04/01/2021, 10:39 AM
    I have two questions about exceptions in Kotlin 1. For sending an exception as a parameter to a function should I use
    fun foo(exc: Exception)
    or
    fun<T : Throwable> foo(exc: KClass<T>)
    2. I can't assign a default value for later
    fun<T : Throwable> foo(exc: KClass<T> = InvalidParamExc::class)
    r
    a
    m
    • 4
    • 12
  • a

    antoniomarin

    04/02/2021, 10:24 AM
    One algorithm question. If I have a following nested object lists, and I want to remove "3" from every `object2`:
    object1: TestType  = [
    	object2=[
    		(...)
    		random = ...,
    		stringList = ["1", "2", "3"]
    	],
        object2(),
        object2(),
        (....)
    ]
    Something like this should work, but I'm wondering is there a more elegant solution? I'm sure there is 😄 I guess I could do a
    object2Mapper
    which could filter "3" as well.
    fun TestType.getWithout3(): TestType {
    	val returnObject = object1
    	returnObject.forEach { object1 ->
    		object1.object2.forEach { object2 ->
    			object2.stringList.toMutableList.removeAll { item == "3"}
    		}
    	}
    	return returnObject
    }
    • 1
    • 1
  • d

    DMITRY.

    04/02/2021, 9:40 PM
    val aggregation = Aggregation.newAggregation(Aggregation.sample(1))
            val commit = mongoOperations.aggregate(aggregation, "commit", Commit::class.java).uniqueMappedResult
            commit?.message
                ?.let { return ResponseEntity<String>(commit.message, HttpStatus.OK) }
                ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "Unable to find commit")
    Does that look like the Kotlin way?
    e
    • 2
    • 3
  • d

    DMITRY.

    04/02/2021, 9:44 PM
    I spent too much time trying to avoid if (commit != null) heh
    e
    • 2
    • 1
  • k

    kqr

    04/03/2021, 12:26 PM
    hello, please is there any way to "fix" this https://pl.kotl.in/oDHhNFTic ?
    y
    a
    t
    • 4
    • 6
  • k

    kqr

    04/03/2021, 2:13 PM
    how can I find all interfaces of a class that are of certain super type? this filter expression is for some reason falsey https://pl.kotl.in/HFvJJCWMO
    :thread-please: 1
    t
    • 2
    • 4
  • a

    Alexander Schell

    04/04/2021, 9:18 AM
    Happy Easter to all of you! :)
    t
    • 2
    • 1
  • m

    Massimiliano Bertinetti

    04/04/2021, 10:34 AM
    Nothing seems to work. I have a jooby and alpas project giving problems with JNA I also try the ktor tutorial here https://ktor.io/docs/creating-interactive-website.html But gradle cannot build, also after upgrading to 6.7
    n
    • 2
    • 7
  • l

    Luis Fer García

    04/05/2021, 3:54 PM
    Hello everyone! I'm new with Kotlin, I'm trying to use Calendar class and I'm having some issues. I'll explain in thread:
    • 1
    • 4
  • h

    Hyugga

    04/06/2021, 3:29 AM
    I'm trying to build kotlin per its instructions, but it seems to require environment variables for 4 Java versions. Why is this?
    v
    d
    • 3
    • 6
  • t

    thhh

    04/06/2021, 1:10 PM
    Help me understand the logic why the code is not returning
    false
    boolean here at once. Details in thread
    h
    t
    +2
    • 5
    • 25
Powered by Linen
Title
t

thhh

04/06/2021, 1:10 PM
Help me understand the logic why the code is not returning
false
boolean here at once. Details in thread
The code could might feel huge, but my only doubt is in the function
find()
inside the if statement
root == null
See if
root == null
is true, then the
find
function must return
false
right? But what happens according to debugging is:
Only should print once BUT it print multiple times (!?) --> null
Only should print once BUT it print multiple times (!?) --> null
Only should print once and it prints one time only as expected!
result true
The important part in the above println logs is
Only should print once BUT it print multiple times (!?) --> null
is
root == null
is true and we are entering the
if
block, so the function
find()
at once MUST return
true
and exit right? But what happens it, the code is seemingly ignoring that and not returning
false
and instead it's keep on executing!! and here is where I am confused! Code below:
class TwoSumIV {
`class TreeNode(var `val`: Int = 0) {`
var left: TreeNode? = null
var right: TreeNode? = null
}
fun findTarget(root: TreeNode?, k: Int): Boolean {
val set: MutableSet<Int?> = HashSet<Int?>()
return find(root, k, set)
}
fun find(root: TreeNode?, k: Int, set: MutableSet<Int?>): Boolean {
if (root == null) {
`println("Only should print once BUT it print multiple times (!?) --> ${root?.
val
}")`
return false
`} else if (set.contains(k - root.
val
)) {`
println("Only should print once and it prints one time only as expected!")
return true
}
`set.add(root.
val
)`
return find(root.left, k, set) || find(root.right, k, set)
}
}
fun main() {
val root = TwoSumIV.TreeNode(5)
root.left = TwoSumIV.TreeNode(3)
root.right = TwoSumIV.TreeNode(6)
println(root)
val twoSumIV = TwoSumIV()
val result = twoSumIV.findTarget(root, 9)
println("result $result")
}
h

Hadji Musaev

04/06/2021, 1:29 PM
Playgrounds are much more fun to use 😉 https://pl.kotl.in/eCNu_QZb8 I simply added a print statement to the case which returns ‘true’ and you can see what happens: k = 9, val = 6 set = [3,5] You check if
k - val
is in the set.
9 - 6 = 3
is indeed present, so it returns
true
.
t

tddmonkey

04/06/2021, 1:31 PM
Why do you think it should only be printed once? By my reckoning it should be printed twice
h

Hadji Musaev

04/06/2021, 1:31 PM
Also,
println
that you expect to only be executed once, will in fact be executed as many times as many leaves you visit before terminating
m

Michael Böiers

04/06/2021, 8:48 PM
`var `val`` … seriously?
🤣 2
t

therealbluepandabear

04/07/2021, 2:31 AM
Change 'val' to 'value'; seriously, it's beyond bizarre.
m

Michael Böiers

04/07/2021, 6:55 AM
Here’s a clean version of the code. Just for fun 🙂 https://pl.kotl.in/J-JC4bMLL
data class Node(val value: Int = 0, val left: Node? = null, val right: Node? = null)

class TwoSumIV {
    fun findTarget(n: Node, k: Int) = find(n, k, HashSet())

    private fun find(n: Node?, k: Int, set: MutableSet<Int>): Boolean = when {
        n == null -> false
        set.contains(k - n.value) -> true
        else -> {
            set.add(n.value)
            with (n) {
                sequenceOf(left, right).any { find(it, k, set) }
            }
        }
    }
}

fun main() {
    Node(5, left = Node(3), right = Node(6)).let {
        println("result ${TwoSumIV().findTarget(it, k = 9)}")
    }
}
t

tddmonkey

04/07/2021, 6:59 AM
No sealed class hierarchy for the Nodes? 😄
And tbh, I find (ha!) your
find
method to be much harder to read than the original
m

Michael Böiers

04/07/2021, 6:59 AM
I misread that - thought you meant the
with
, which was a little over the top.
t

tddmonkey

04/07/2021, 7:10 AM
I do now wonder if a sealed class hierarchy (Node, NoNode, SomeNode) might clean that up
m

Michael Böiers

04/07/2021, 7:20 AM
What do you mean - the nullable children?
Here’s a more concise version using an extension function. Still using
with
just because I can’t use a block of code in the boolean expression directly.
data class Node(val value: Int = 0, val left: Node? = null, val right: Node? = null) {
    val children = sequenceOf(left, right)
}

class TwoSumIV {
    fun findTarget(n: Node, k: Int) = n.find(k, HashSet())

    private fun Node.find(k: Int, set: MutableSet<Int>): Boolean =
        set.contains(k - value) || with (children) {
            set.add(value)
            filterNotNull().any { it.find(k, set) }
        }
}


fun main() {
    Node(5, left = Node(3), right = Node(6)).let {
        println(it)
        println("result ${TwoSumIV().findTarget(it, k = 9)}")
    }
}
Damn, refactoring is like a rabbit hole. 😉
data class Node(val value: Int = 0, val left: Node? = null, val right: Node? = null) {
    val children = listOfNotNull(left, right)
}

class TwoSumIV {
    fun findTarget(n: Node, k: Int) = n.find(k, HashSet())

    private fun Node.find(k: Int, set: MutableSet<Int>): Boolean =
        k - value in set || with (children) {
            set += value
            any { it.find(k, set) }
        }
}

fun main() {
    Node(5, left = Node(3), right = Node(6)).let {
        println(it)
        println("result ${TwoSumIV().findTarget(it, k = 9)}")
    }
}
t

tddmonkey

04/07/2021, 8:32 AM
sealed class TreeNode(val value: Int) {
    abstract fun find(k: Int): Boolean
}

class LeafNode(value: Int): TreeNode(value) {
    override fun find(k: Int): Boolean {
        return value == k
    }
}

class BranchNode(value: Int, val left: TreeNode, val right: TreeNode): TreeNode(value) {
    override fun find(k: Int): Boolean {
        if (value == k) {
            return true
        }
        return left.find(k) || right.find(k)
    }
}

class TwoSumIV {
    fun findTarget(root: TreeNode, k: Int): Boolean {
        return root.find(k)
    }
}
fun main() {
    val root = BranchNode(5, left = LeafNode(3), right = LeafNode(6))
    println(root)
    val twoSumIV = TwoSumIV()
    println("Tree has 6 -> ${twoSumIV.findTarget(root, 6)}")
    println("Tree has 9 -> ${twoSumIV.findTarget(root, 9)}")
}
m

Michael Böiers

04/07/2021, 8:42 AM
Isn’t this more concise?
data class Node(val value: Int, val left: Node? = null, val right: Node? = null) {
    private val children = listOfNotNull(left, right)
    fun find(k: Int): Boolean = value == k || children.any { it.find(k) }
}

fun leafOf(value: Int) = Node(value)
fun branchOf(value: Int, left: Node, right: Node) = Node(value, left, right)

class TwoSumIV {
    fun findTarget(root: Node, k: Int) = root.find(k)
}

fun main() {
    val root = branchOf(5, left = leafOf(3), right = leafOf(6))
    val twoSumIV = TwoSumIV()
    println("Tree has 6 -> ${twoSumIV.findTarget(root, 6)}")
    println("Tree has 9 -> ${twoSumIV.findTarget(root, 9)}")
}
I think that if you go for the sealed class hierarchy there should be some when/smart casting involved 🙂
t

tddmonkey

04/07/2021, 8:52 AM
Not sure if you’re being serious or not?
m

Michael Böiers

04/07/2021, 8:56 AM
I just don’t see the benefit of the class hierarchy in your code. I haven’t used sealed class hierarchies much, but the main use case that I have seen is that you can write elegant when expressions using smart casting in the branches.
But of course your code is perfectly fine, it’s proper use of inheritance in terms of the “is a” criterion. I just tend to avoid using inheritance wherever possible.
t

tddmonkey

04/07/2021, 9:15 AM
I also prefer to avoid inheritance, but in this instance it’s really just an interface implemented by 2 classes. A sealed hierarchy brings the ability to control the implementations of it. It also allows me to avoid handling nulls as that’s now modelled by a
LeafNode
.
m

Michael Böiers

04/07/2021, 10:07 AM
Sure. This is what I meant with the when/smart cast stuff:
sealed class Node {
    data class Leaf(val value: Int) : Node()
    data class Branch(val value: Int, val left: Node, val right: Node) : Node()

    fun find(k: Int): Boolean = when (this) {
        is Leaf -> k == value
        is Branch -> k == value || left.find(k) || right.find(k)
    }
}


class TwoSumIV {
    fun findTarget(root: Node, k: Int): Boolean {
        return root.find(k)
    }
}

fun main() {
    val root = Node.Branch(5, left = Node.Leaf(3), right = Node.Leaf(6))
    println(root)
    val twoSumIV = TwoSumIV()
    println("Tree has 6 -> ${twoSumIV.findTarget(root, 6)}")
    println("Tree has 9 -> ${twoSumIV.findTarget(root, 9)}")
}
t

tddmonkey

04/07/2021, 10:36 AM
Oh yeah totally, I think I just prefer moving the logic to the implementing class
m

Michael Böiers

04/07/2021, 10:58 AM
This comes down to preferences about encapsulation and object-oriented programming. I tend to gravitate more towards the functional approach. Personally I don’t think that one is better or worse than the other. 🙂 Sorry @thhh for derailing this thread a little, but I think your question had been answered before 🙂
❤️ 1
h

Hadji Musaev

04/07/2021, 5:32 PM
@Michael Böiers @therealbluepandabear I think I ran into the reason why ‘var `val`’ is used 🙂 It comes from leetcode problems and probably they use it to align names with other languages:
/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
🙌 2
View count: 2