标签: kotlin-sealed

kotlin中密封类与密封接口有什么区别

随着 Kotlin1.5的推出sealed interface,. 即使我知道类和接口之间的区别,我也不清楚使用sealed interfaceover的最佳实践和好处是什么sealed class

interface即使是简单的情况,我是否应该始终使用now ?还是将视具体情况而定?

谢谢

Obs:没有发现类似的问题,只是关于sealed classes

interface kotlin sealed-class kotlin-sealed

55
推荐指数
2
解决办法
2万
查看次数

如何修复 Kotlin 中的“密封类/接口上的非详尽‘when’语句”

Kotlin 1.7when中将禁止对密封类/接口进行非详尽的声明。

我有一个sealed class State和它的孩子:

sealed class State {
    object Initializing : State()
    object Connecting : State()
    object Disconnecting : State()
    object FailedToConnect : State()
    object Disconnected : State()
    object Ready : State()
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,我只想处理特定的项目,而不是全部,例如:

val state: State = ... // initialize
when (state) {
    State.Ready -> { ... }
    State.Disconnected -> { ... }
}
Run Code Online (Sandbox Code Playgroud)

但我收到一条警告(在Kotlin 1.7中我猜这将是一个错误),说:

1.7 中将禁止在密封类/接口上使用非详尽的“when”语句,而是添加“Connecting”、“Disconnecting”、“FailedToConnect”、“Initializing”分支或“else”分支

else -> {}像下面的代码一样在这里使用空分支是一个好习惯吗?

when (state) {
    State.Ready -> { ... }
    State.Disconnected -> …
Run Code Online (Sandbox Code Playgroud)

android kotlin sealed-class kotlin-when kotlin-sealed

9
推荐指数
1
解决办法
1万
查看次数

如何在 kotlin 中使用带有泛型的密封类`

我有以下课程,但我正在努力解决泛型问题


sealed class Result<T,E> {
    data class Success<T>(val data: T): Result<T,Void>()
    data class Failure<E>(val error: E): Result<Void,E>()
}


fun interface SeqListener<T,E> {
    fun onComplete(result: Result<T,E>)
}

abstract class Seq<T,E> {

    var started = false
        private set

    var complete = false
        private set

    private lateinit var seqListener: SeqListener<T,E>

    fun start(listener: SeqListener<T,E>) {
        if (!started) {
            seqListener = listener
            started = true
            return doStart()
        } else throw IllegalStateException("cannot call start on a sequence more than once")
    }

    fun success(result: Result.Success<T>) {
        complete(result) …
Run Code Online (Sandbox Code Playgroud)

generics kotlin sealed-class kotlin-sealed

2
推荐指数
1
解决办法
833
查看次数

使用数据类型对函数类型进行约束

我对数据类型感到困惑。假设我们有

{-# LANGUAGE DataKinds #-}
...
data Format
  = Photo
      { bytes :: Int
      }
  | Video
      { bytes       :: Int
      , durationSec :: Int
      }
Run Code Online (Sandbox Code Playgroud)

我想让 then 具有提升类型的功能:

createVideo :: Int -> Int -> 'Video
createVideo _ _ = error "Not implemented"
Run Code Online (Sandbox Code Playgroud)

编译器会询问我们参数,并用它们给出消息“Video Int Int has kind ‘Format’”。我希望这种编译时行为类似于 kotlin:

sealed class Format {

  abstract val bytes: Int
  data class Photo(override val bytes: Int) : Format()
  data class Video(override val bytes: Int, val durationSec: Int) : Format()
}

private fun …
Run Code Online (Sandbox Code Playgroud)

haskell types functional-programming data-kinds kotlin-sealed

2
推荐指数
1
解决办法
255
查看次数