Advertisement
Kostiggig

String from a nullable value

May 19th, 2022
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.22 KB | None | 0 0
  1. interface NotNullValue {
  2.  
  3.     fun string() : kotlin.String
  4.  
  5.     abstract class Base<T : Any?>(
  6.         private val src: T?,
  7.         private val default: kotlin.String = DEFAULT_VALUE
  8.     ) : NotNullValue {
  9.  
  10.         abstract fun uniqueCondition() : Boolean
  11.  
  12.         override fun string(): kotlin.String {
  13.             return if (src == null || uniqueCondition()) {
  14.                 default
  15.             } else {
  16.                 src.toString()
  17.             }
  18.         }
  19.  
  20.         private companion object {
  21.             private const val DEFAULT_VALUE = "Unknown"
  22.         }
  23.     }
  24.     class Int(
  25.         src: kotlin.Int?
  26.     ) : Base<kotlin.Int?>(src) {
  27.  
  28.         override fun uniqueCondition() = false
  29.     }
  30.  
  31.     class Double(
  32.         private val src: kotlin.Double?
  33.     ) : Base<kotlin.Double?>(src) {
  34.  
  35.         override fun uniqueCondition() = src == NEGATIVE_VALUE
  36.  
  37.         private companion object {
  38.             private const val NEGATIVE_VALUE = -1.0
  39.         }
  40.     }
  41.  
  42.     class String(
  43.         private val src: kotlin.String?
  44.     ) : Base<kotlin.String?>(src) {
  45.  
  46.         override fun uniqueCondition() = src.isNullOrEmpty()
  47.     }
  48.  
  49.     object Empty : NotNullValue {
  50.         override fun string() = ""
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement