Skip to content

Instantly share code, notes, and snippets.

@joshlong
Last active March 4, 2020 20:03
Show Gist options
  • Select an option

  • Save joshlong/2602aed9d1dd0c48c32d6c69a2f746f5 to your computer and use it in GitHub Desktop.

Select an option

Save joshlong/2602aed9d1dd0c48c32d6c69a2f746f5 to your computer and use it in GitHub Desktop.
package com.example.fourteen;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.util.Assert;
import java.util.Date;
import java.util.List;
@Log4j2
@SpringBootApplication
public class FourteenApplication {
public static void main(String[] args) {
SpringApplication.run(FourteenApplication.class, args);
}
@EventListener(ApplicationReadyEvent.class)
public void go() {
// multiline strings AND auto type inference
var sql =
"""
Would this work correctly if
I added it to a traditional
application?
""".strip();
log.info(sql);
// convenient collection literals
var listOfPeople = List.of(
new Person("jlong", new Date()),
new Person("rwinch", new Date())
);
// lambdas
listOfPeople.forEach(person -> log.info(person.username()));
// or method references!
listOfPeople.forEach(log::info);
// this pointer is (forcibly) Object so...
var next = (Object) listOfPeople.iterator().next();
// Let's use a smart cast...
if (next instanceof Person p) {
Date birthday = p.birthday();
String username = p.username();
log.info("this particular birthday is " + birthday);
log.info("this particular username is " + username);
log.info(p);
}
// switch expressions
var dev = new Developer(Math.random() < .5 ? EmotionalState.NOT_WRITING_CODE : EmotionalState.WRITING_CODE);
var message = switch (dev.currentStatus()) {
case NOT_WRITING_CODE -> "Why wake up?";
case WRITING_CODE -> "I love writing code!";
};
log.info(message);
}
}
// still loving enums
enum EmotionalState {
NOT_WRITING_CODE,
WRITING_CODE
}
// records are like case classes or data classes in other languages
// records work just fine like this
record Developer(EmotionalState currentStatus) {
}
// or they can have 'compact' constructors
record Person(String username, Date birthday) {
public Person {
Assert.notNull(username, "the username is not null");
Assert.notNull(birthday, "the birthday is not null");
this.username = username.toUpperCase();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment