Last active
August 30, 2018 09:57
-
-
Save adibfara/c2746438439548d76372464a43ac6764 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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