Skip to content

Instantly share code, notes, and snippets.

Avatar

Jarno Walgemoed jwalgemoed

View GitHub Profile
View measuretime.kt
fun main(args: Array<String>) {
var assign: String
val time = measureTimeMillis {
assign = "Value Assigned"
}
println("$time ms. spent assigning: '$assign!!'")
}
private inline fun measureTimeMillis(block: () -> Unit): Long {
val start = System.currentTimeMillis()
View measuretimeContract.kt
@ExperimentalContracts
fun main(args: Array<String>) {
var assign: String
val time = measureTimeMillis {
assign = "Value Assigned"
}
println("$time ms. spent assigning: '$assign'")
}
@ExperimentalContracts
View use.kt
fun printUserDetails(user: User?) {
if(user?.isValid()) {
println("${user.name} ${user.email}")
}
}
View usage2.kt
fun printUserDetails(user: User?) {
if(user.isComplete()) {
println("${user!!.name} ${user!!.email}")
}
}
View contract.kt
contract {
returns(true) implies (this@isComplete != null)
}
View withcontract.kt
@ExperimentalContracts
fun User?.isComplete(): Boolean {
contract { returns(true) implies (this@isComplete != null) }
return this != null && this.isValid()
}
View userclass.kt
data class User(val name: String?, val email: String?) {
fun isValid() = !name.isNullOrBlank() && name.length > 3
&& !email.isNullOrBlank() && email.length > 3
}
View example3.java
var strings = Arrays.asList("a", "b", "c");
for(var str: strings) {
System.out.println(str);
}
View method.java
var variable = returnValue(); // Type is inferred from the return type of the method
// Method declaration
public String returnValue() {
return "w00p";
}
View example2.java
// Can't use the local variable type inference with fields
public class SomeClass {
// Not allowed, var is only available for local variables
var property = "";
}
// Can't leave values unitialzed
var uninitialized; // No way to infer the type
// Can't just assign null to var to reassign later (but workaround available)