Leoš Přikryl
@leos_prikryl
commity.cz, GDG Jihlava
val a: Int = 2 //immutable var b: String = "Hello" //mutable
val a = 2 var b = "Hello" val myClass = MyClass()
var a = 2;
val list = listOf(1, 2, 3) //immutable val list = mutableListOf(1, 2, 3) //mutable val map = mapOf(1 to "one", 2 to "two") //immutable val map = mutableMapOf(1 to "one", 2 to "two") //mutable
List<Integer> list = List.of(1, 2, 3); //immutable :-o
var max: Int
if (a > b) {
max = a
} else {
max = b
}
val max = if (a > b) a else b
var text: String
when (x) {
1 -> text = "jedna"
2 -> text = "dvě"
else -> {
text = "mnoho"
}
}
val text = when (x) {
1 -> "jedna"
2 -> "dvě"
else -> {
"mnoho"
}
}
val text = when (x) { 1, 2 -> "jedna nebo dvě" in 3..10 -> "tři až deset" else -> "mnoho" }
var text = switch (x) { case 1, 2 -> "jedna nebo dvě"; case 3, 4, 5, 6, 7, 8, 9, 10 -> "tři až deset"; default -> "mnoho"; };
when { x.isOdd() -> println("x je liché") x.isEven() -> println("x je sudé") else -> throw IllegalNumberException() }
if (x.isOdd()) { System.out.println("x je liché"); } else if (x.isEven()) { System.out.println("x je sudé"); } else { throw new IllegalNumberException(); }
fun sum(a: Int, b: Int = 0): Int { return a + b }
public int sum(int a, int b) { return a + b; } public int sum(int a) { return sum(a, 0); }
val c = sum(a = 5, b = 10)
public inline fun measureTimeMillis(block: () -> Unit) : Long {
val start = System.currentTimeMillis()
block()
return System.currentTimeMillis() - start
}
val doubled = ints.map({ value -> value * 2 })
val doubled = ints.map { it * 2 }
val elapsedTime = measureTimeMillis {
doSomeWork()
}
public class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
class User (var name: String)
public class User { private String name; public User(String name) {...} public String getName() {...} public void setName(String name) {...} @Override public boolean equals(Object o) {...} @Override public int hashCode() {...} @Override public String toString() {...} public User copy(String name) {...} }
data class User (var name: String)
data class User(val name: String = "", val email: String = "") val user = User(name = "Petr") val user2 = user.copy(email = "petr@gmail.com")
val person1 = Person("Petr") val person2 = Person("Petr") person1 == person2 //true - automaticky volá .equals() person1 === person2 //false - porovnává reference
String s = "Rozměry: " + width + " x " + height + " metrů";
String s = String.format("Rozměry: %d x %d metrů", width, height);
val s = "Rozměry: $width x $height metrů"
String sql = "SELECT\n" + " fist_name,\n" + " last_name,\n" + " email\n" + "FROM users\n" + "WHERE id = ?";
val sql = """SELECT fist_name, last_name, email FROM users WHERE id = ?"""
var sql = `SELECT fist_name, last_name, email FROM users WHERE id = ?`
if (obj instanceof String) { System.out.println(((String) obj).toLowerCase()); }
if (obj is String) { println(obj.toLowerCase()); }
if (value instanceof Number) { cell.setDoubleValue(((Number)value).toDouble()); } else if (value instanceof Date) { cell.setDateValue((Date)value); } else { cell.setStringValue(value.toString()); }
when (value) { is Number -> cell.setDoubleValue(value.toDouble()) is Date -> cell.setDateValue(value) else -> cell.setStringValue(value.toString()) }
public class Singleton { private static Singleton instance = null; private Singleton(){ } private static void getInstance() { if(instance == null){ synchronized (Singleton.class) { if(instance == null){ instance = new Singleton(); } } } return instance; } }
object Singleton
private ExpensiveObject expensiveObject; public ExpensiveObject getExpensiveObject() { if(expensiveObject == null) { synchronized(this) { if(expensiveObject == null) { expensiveObject = new ExpensiveObject(); } } } return expensiveObject; }
val expensiveObject by lazy { ExpensiveObject() }
var notNullString: String = "Hello" notNullString = null //compilation error
var nullableString: String? = "Hello" notNullString = null //OK
fun getZipForUser(user: User?): String? { return user?.address?.zip }
public String getZipForUser(User user) { if (user != null && user.getAddress() != null) { return user.getAddress().getZip(); } else { return null; } }
val locationService = getLocationService() val location = locationService?.findLocation() if (location != null) { println("${location.longitude}, ${location.latitude}") }
LocationService locationService = getLocationService(); if (locationService != null) { Location location = locationService.findLocation(); if (location != null) { println(location.longitude + ", " + location.latitude); } }
val displayName = username ?: "N/A"
String displayName = username != null ? username : "N/A";
fun getUserById(id: Long) : User { return userRepository.findOne(id) ?: throw UserNotFoundException() }
User getUserById(long id) { User user = userRepository.findOne(id); if (user == null) { throw new UserNotFoundException(); } return user; }
val user: User? = findUserById(42) if (user != null) { println(user.address) //user is not null }
val text: String? = getText() if (!text.isNullOrBlank()) { println(text.length) //text is not null }
val lock = Object()
val x: Int
synchronized(lock) {
x = 42
}
println(x)
public fun String.capitalize(): String { return if (isNotEmpty()) { substring(0, 1).toUpperCase() + substring(1) } else { this } }
StringUtils.capitalize(string);
string.capitalize()
List<String> oldList = Arrays.asList("a1", "a2", "b1", "c2", "c1"); List<String> transformedList = oldList .stream() .filter(s -> s.startsWith("c")) .map(String::toUpperCase) .sorted() .collect(Collectors.toList());
val oldList = listOf("a1", "a2", "b1", "c2", "c1") val transformedList = oldList .filter { it.startsWith("c") } .map { it.toUpperCase() } .sorted()
fun postItem(item: Item) {
val token = login()
val post = submitPost(token, item)
processPost(post)
}
fun login(): Token {
// a blocking code
return token
}
fun postItem(item: Item) {
loginAsync { token ->
submitPostAsync(token, item) { post ->
processPost(post)
}
}
}
fun loginAsync(callback: () -> Token) {
// make request and return immediately
// arrange callback to be invoked later
}
suspend fun postItem(item: Item) {
val token = login()
val post = submitPost(token, item)
processPost(post)
}
suspend fun login(): Token {
}
GlobalScope.launch {
syncData()
}
val deferredData : Deferred<Data> = GlobalScope.async {
retrieveData()
}
val job = GlobalScope.launch {
syncData()
}
job.cancel();
try {
GlobalScope.launch {
syncData()
}
} catch (e: DataSynchronizationException) {
//handle exception
}
suspend fun loadImage(url: String): Image {
// blocking load
}
suspend fun getCombinedImage(url1: String, url2: String): Image {
val image1 = loadImage(url1)
val image2 = loadImage(url2)
return combineImages(image1, image2)
}
suspend fun loadImage(url: String): Image {
// blocking load
}
suspend fun getCombinedImage(url1: String, url2: String): Image {
val image1 = GlobalScope.async { loadImage(url1) }
val image2 = GlobalScope.async { loadImage(url2) }
return combineImages(image1.await(), image2.await())
}
suspend fun loadImage(url: String): Image {
// blocking load
}
suspend fun getCombinedImage(url1: String, url2: String): Image {
return coroutineScope {
val image1 = async { loadImage(url1) }
val image2 = async { loadImage(url2) }
combineImages(image1.await(), image2.await())
}
}
val file = File("temp.tmp") if (file.exists()) { println("File exists") }
public class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
val user = User("John") println(user.name)
//Executor.java void execute(Runnable command) { ... }
executor.execute { println("runnable") }
public class Generator { public String generateString() { return ...; } }
val s = Generator().generateString() // String!
val s: String? = Generator().generateString() // vždy projde
val s: String = Generator().generateString() // může vyhodit NPE v runtime
public class Generator { @NotNull public String generateString() { return ...; } }
val s = Generator().generateString() // String
public class Generator { @Nullable public String generateString() { return ...; } }
val s = Generator().generateString() // String?