今天继续学习了Android中的kotlin语言
初始Java语言
mport java.util.ArrayList; import java.util.List; public class Repository { private static final Repository INSTANCE = null; private List<User> users = null; public static Repository getInstance() { if (INSTANCE == null) { synchronized (Repository.class) { if (INSTANCE == null) { INSTANCE = new Repository(); } } } return INSTANCE; } // keeping the constructor private to enforce the usage of getInstance private Repository() { User user1 = new User("Jane", ""); User user2 = new User("John", null); User user3 = new User("Anne", "Doe"); users = new ArrayList(); users.add(user1); users.add(user2); users.add(user3); } public List<User> getUsers() { return users; } public List<String> getFormattedUserNames() { List<String> userNames = new ArrayList<>(users.size()); for (User user : users) { String name; if (user.getLastName() != null) { if (user.getFirstName() != null) { name = user.getFirstName() + " " + user.getLastName(); } else { name = user.getLastName(); } } else if (user.getFirstName() != null) { name = user.getFirstName(); } else { name = "Unknown"; } userNames.add(name); } return userNames; } }
转化后:
class Repository // keeping the constructor private to enforce the usage of getInstance private constructor() { private val users: MutableList<User>? = null // ?= 表示可空 val formattedUserNames: List<String> get() { val userNames = ArrayList<String>(users!!.size) for ((firstName, lastName) in users) { val name: String? if (lastName != null) { if (firstName != null) { name = "$firstName $lastName" } else { name = lastName } } else if (firstName != null) { name = firstName } else { name = "Unknown" } userNames.add(name) } return userNames } init { val user1 = User("Jane", "") val user2 = User("John", null) val user3 = User("Anne", "Doe") users = ArrayList() users!!.add(user1) users.add(user2) users.add(user3) } fun getUsers(): List<User>? { return users } companion object { private var INSTANCE: Repository? = null val instance: Repository get() { if (INSTANCE == null) { synchronized(Repository::class.java) { if (INSTANCE == null) { INSTANCE = Repository() } } } return INSTANCE } } }
执行了:
- 添加了
init
代码块 (Repository.kt#L33) static
字段现已加入companion object
代码块中 (Repository.kt#L48)users
列表可为 null,因为该对象在声明时并未实例化 (Repository.kt#L9)getFormattedUserNames()
方法现已成为一个属性 (Repository.kt#L11)- 在对用户列表执行循环时,其语法与 Java 不同 (Repository.kt#L14)
标签:01,users,Repository,05,INSTANCE,User,2023,null,name From: https://www.cnblogs.com/JJTyyds/p/17367110.html