Best way to handle such scenario where “smart cast is imposible”

前端 未结 7 803
鱼传尺愫
鱼传尺愫 2020-12-20 17:33

I wonder what is the best way to handle such scenario

class Person(var name:String? = null, var age:Int? = null){
    fun test(){
        if(name != null &am         


        
7条回答
  •  旧巷少年郎
    2020-12-20 18:26

    In addition to miensol's answer there are various ways to copy property values into function variables to enable smart cast. e.g.:

    1. Intermediary function:

      class Person(var name: String? = null, var age: Int? = null) {
          fun test() = test(name, age)
          private fun test(name: String?, age: Int?) {
              if (name != null && age != null)
                  doSth(name, age) //smart cast possible
          }
      
          fun doSth(someValue: String, someValue2: Int) {
      
          }
      }
      
    2. Anonymous function:

      class Person(var name: String? = null, var age: Int? = null) {
          fun test() = (fun(name: String?, age: Int?) {
              if (name != null && age != null)
                  doSth(name, age) //smart cast possible
          })(name, age)
      
          fun doSth(someValue: String, someValue2: Int) {
      
          }
      }
      
    3. Default arguments:

      class Person(var name: String? = null, var age: Int? = null) {
          fun test(name: String? = this.name, age: Int? = this.age) {
              if (name != null && age != null)
                  doSth(name, age) //smart cast possible
          }
      
          fun doSth(someValue: String, someValue2: Int) {
      
          }
      }
      

提交回复
热议问题