vsr
03/16/2021, 3:54 PM./gradlew run
) after making code changes. Is there a hot module reloading concept in Kotlin (coming from a frontend background) 🙂tseisel
03/16/2021, 3:58 PMFlow
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.Nate Emmons
03/17/2021, 3:29 PMVarun
03/19/2021, 3:11 PMVarun
03/20/2021, 4:08 AMtherealbluepandabear
03/20/2021, 10:30 PMthhh
03/21/2021, 9:56 AMimport 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▾
https://i.imgur.com/1unP2hY.gif▾
Daniele B
03/21/2021, 1:42 PMScreenState
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> {
}
Daniele B
03/21/2021, 5:35 PMinline fun <reified T:Any> getResponse(endpoint : String): T? {
val newObj = T()
....
}
Daniele B
03/22/2021, 10:33 AMfun 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)
Kenneth
03/22/2021, 1:42 PMallan.conda
03/24/2021, 9:52 AMsealed 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?diego.brum
03/24/2021, 3:30 PMvar (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#?Jonathan Olsson
03/25/2021, 7:57 AM@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.
Jonathan Olsson
03/25/2021, 11:45 AMenum class Status(val value: Int) {
Ok(0),
NotOk(1),
SomeOtherStatus(2)
}
jbruckne
03/25/2021, 8:24 PMimplementation('com.example:MyKMMProject-jvm:1.0')
?JsebasCT
03/26/2021, 12:25 PMDMITRY.
03/30/2021, 11:21 AMmongoOperations.findAndModify(searchQuery, update, T::class.java)
Cannot use 'T' as reified type parameter. Use a class instead.
How make it work?Dennis Tel
03/31/2021, 5:01 PM.windowed
but not sure if this is the way to go. Pretty new to Kotlin and the JVM 😬Arrow
04/01/2021, 10:39 AMfun 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)
antoniomarin
04/02/2021, 10:24 AMobject1: 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
}
DMITRY.
04/02/2021, 9:40 PMval 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?DMITRY.
04/02/2021, 9:44 PMkqr
04/03/2021, 12:26 PMkqr
04/03/2021, 2:13 PMAlexander Schell
04/04/2021, 9:18 AMMassimiliano Bertinetti
04/04/2021, 10:34 AMLuis Fer García
04/05/2021, 3:54 PMHyugga
04/06/2021, 3:29 AMthhh
04/06/2021, 1:10 PMfalse
boolean here at once.
Details in threadthhh
04/06/2021, 1:10 PMfalse
boolean here at once.
Details in threadfind()
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")
}
Hadji Musaev
04/06/2021, 1:29 PMk - val
is in the set. 9 - 6 = 3
is indeed present, so it returns true
.tddmonkey
04/06/2021, 1:31 PMHadji Musaev
04/06/2021, 1:31 PMprintln
that you expect to only be executed once, will in fact be executed as many times as many leaves you visit before terminatingMichael Böiers
04/06/2021, 8:48 PMtherealbluepandabear
04/07/2021, 2:31 AMMichael Böiers
04/07/2021, 6:55 AMdata 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)}")
}
}
tddmonkey
04/07/2021, 6:59 AMfind
method to be much harder to read than the originalMichael Böiers
04/07/2021, 6:59 AMwith
, which was a little over the top.tddmonkey
04/07/2021, 7:10 AMMichael Böiers
04/07/2021, 7:20 AMwith
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)}")
}
}
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)}")
}
}
tddmonkey
04/07/2021, 8:32 AMsealed 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)}")
}
Michael Böiers
04/07/2021, 8:42 AMdata 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)}")
}
tddmonkey
04/07/2021, 8:52 AMMichael Böiers
04/07/2021, 8:56 AMtddmonkey
04/07/2021, 9:15 AMLeafNode
.Michael Böiers
04/07/2021, 10:07 AMsealed 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)}")
}
tddmonkey
04/07/2021, 10:36 AMMichael Böiers
04/07/2021, 10:58 AMHadji Musaev
04/07/2021, 5:32 PM/**
* 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
* }
*/