Skip to content

Instantly share code, notes, and snippets.

@adibfara
Last active August 30, 2018 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adibfara/c2746438439548d76372464a43ac6764 to your computer and use it in GitHub Desktop.
Save adibfara/c2746438439548d76372464a43ac6764 to your computer and use it in GitHub Desktop.
/**
* @author Adib Faramarzi (adibfara@gmail.com)
*/
fun Any?.isAValidName():Boolean{
return this!=null && this is String && this.length > 3
}
fun getName():String? { ... }
fun testUserName(){
val name = getName()
if(name.isAValidName()){
// compile error: Type mismatch: String is expected but String? was found.
val fullName:String = name
}
}
/**
* @author Adib Faramarzi (adibfara@gmail.com)
*/
@ExperimentalContracts
fun Any?.isAValidName():Boolean{
contract {
returns(true) implies (this@isAValidName is String)
}
return this!=null && this is String && this.length > 3
}
fun getName():String? { ... }
@ExperimentalContracts
fun testUserName(){
val name = getName()
if(name.isAValidName()){
// No compile error! The compiler knows that because we told it with `implies`.
val fullName:String = name
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment