Update & get value of variable during execution time

I am using Android Studio with Gradle build. In my build.gradle, I want a variable’s value to be updated for different build type:

ext {
    //By default, the value of myVar is 'debug'
    myVar = 'debug'
}
  android {
   buildTypes {
       release {
                //update value of myVar to 'release'
            project.ext.set("myVar","release")
        }
            debug {
             //update value of myVar to 'debug'
             project.ext.set("myVar","debug")
        }
      }
}
  //I defined a task to check the value of myVar
task checkVar () {
   println "My var is $myVar"
}
  check.dependsOn(checkVar)

When I run command

gradle clean assembleRelease

I expected to see a print out text “My var is release”. But, I see " My var is debug ". Why the value of myVar is not changed to release ?

What I want to achieve is to get the current build type during task execution. What is the correct way to achieve this?