我知道内联函数可能会提高性能并导致生成的代码增长,但我不确定何时正确使用它.
lock(l) { foo() }
Run Code Online (Sandbox Code Playgroud)
编译器可以发出以下代码,而不是为参数创建函数对象并生成调用.(来源)
l.lock()
try {
foo()
}
finally {
l.unlock()
}
Run Code Online (Sandbox Code Playgroud)
但我发现kotlin没有为非内联函数创建的函数对象.为什么?
/**non-inline function**/
fun lock(lock: Lock, block: () -> Unit) {
lock.lock();
try {
block();
} finally {
lock.unlock();
}
}
Run Code Online (Sandbox Code Playgroud) 例如,在以下两个代码中:
File("./file1.txt").forEachLine { println(it) }
Run Code Online (Sandbox Code Playgroud)
和
File("somefile.txt").bufferedWriter().use { out ->
history.forEach {
out.write("${it.key}, ${it.value}\n")
}
}
Run Code Online (Sandbox Code Playgroud)
在这段代码中it
意味着什么?
如果我在Kotlin中有一个对象的集合,有没有一种快速的方法来获取这些对象的某个属性的集合?我查看了Kotlin的收集操作列表,但没有什么能让我感到高兴(但我可能忽略了一些东西)
在python中它将类似于:
[person.name for person in persons]
而且我更喜欢使用集合函数而不是:
var nameMap = mutableListOf<String>()
persons.forEach{person -> nameMap.add(person.name)}
Run Code Online (Sandbox Code Playgroud)
我非常缺乏过滤/ lambda函数以及除列表理解之外的任何知识,所以如果这是一个简单的问题就道歉
我有一个extension
方法,在Kotlin中将字符串转换为Date.
fun String.convertToDate() : Date {
var pattern: String = "dd-mm-yyyy"
val dateFormatter = SimpleDateFormat(pattern)
return dateFormatter.parse(this) // parse method throw ParseException
}
Run Code Online (Sandbox Code Playgroud)
这是我试图捕获可能的异常的代码.
try {
"22---2017".convertToDate()
} catch (ex: ParseException) {
// ParseException supposed to be caught in this block
logger.error("Parse exception occur")
} catch (ex: Exception) {
// ParseException caught in this block
logger.error("Exception occur")
}
Run Code Online (Sandbox Code Playgroud)
在ParseException
过去块就是抓住了Exception
被捕获.但它应该在ParseException块中捕获吗?我在这里错过了什么?
=== 更新 ===
我正在开发一个Spring MVC项目.我已经在简单的独立kotlin程序中运行代码,其中它的行为相应.但在我的春季项目中,它表现不同.我给出了完整的代码Controller
和Service
图层.
调节器
@PostMapping
@PreAuthorize("hasAnyRole('USER','ROLE_USER','ROLE_ADMIN','ADMIN')")
fun postAttendance(@RequestBody attendanceJson: …
Run Code Online (Sandbox Code Playgroud) 我CharArray
的内容是如下字符:
val chars = arrayOf('A', 'B', 'C')
Run Code Online (Sandbox Code Playgroud)
要么
val chars = "ABC".toCharArray()
Run Code Online (Sandbox Code Playgroud)
我想从中获取字符串"ABC"
.我该怎么做?
chars.toString()
不起作用; 它就好像chars
是一个普通的整数数组.
我想知道,作为一个新手Kotlin编码器,是否有一些良好的实践甚至语言结构来声明函数的前置条件.
在Java中,我一直在使用Guava的Preconditions检查实用程序:
https://github.com/google/guava/wiki/PreconditionsExplained
经过一些进一步的调查后,我遇到了require函数:
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/require.html
这通常用于检查函数的前提条件吗?
我已经解决了Y-combinator问题.刚才我发现我不能递归地引用泛型参数.
Y = ?f.(?x.f (x x)) (?x.f (x x))
Run Code Online (Sandbox Code Playgroud)
例如:
IntUnaryOperator fact = Y(rec -> n -> n == 0 ? 1 : n * rec.applyAsInt(n - 1));
IntUnaryOperator Y(Function<IntUnaryOperator, IntUnaryOperator> f) {
return g(g -> f.apply(x -> g.apply(g).applyAsInt(x)));
}
IntUnaryOperator g(G g) {
return g.apply(g);
}
// v--- I want to remove the middle-interface `G`
interface G extends Function<G, IntUnaryOperator> {/**/}
Run Code Online (Sandbox Code Playgroud)
问:如何在方法上使用泛型参数g
以避免引入额外的接口G
,并且泛型参数应该避免UNCHECKED
警告?
提前致谢.
public class Test {
static List<Object> listA = new ArrayList<>();
public static void main(final String[] args) {
final List<TestClass> listB = new ArrayList<>();
listB.add(new TestClass());
// not working
setListA(listB);
// working
setListA(listB.stream().collect(Collectors.toList()));
System.out.println();
}
private static void setListA(final List<Object> list) {
listA = list;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么它适用于流,并不适用于简单的集合?
我们正在将项目转移到Kotlin语言.我们决定从测试开始,但面临一些奇怪的行为.
这是我们的测试用例:
Service.java
public final class Service {
private final JdbcTemplate jdbcTemplate;
public Service(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public long check() {
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM table", Long.class);
}
}
Run Code Online (Sandbox Code Playgroud)
JavaTest.java(工作正常)
@RunWith(MockitoJUnitRunner.class)
public final class JavaTest {
@Mock
private JdbcTemplate jdbcTemplate;
@InjectMocks
private Service testSubject;
@Test
public void test() {
//given
when(jdbcTemplate.queryForObject(anyString(), eq(Long.class))).thenReturn(1L);
//when
long result = testSubject.check();
//then
assertThat(result, is(1L));
}
}
Run Code Online (Sandbox Code Playgroud)
KotlinTest.kt(不工作)
@RunWith(MockitoJUnitRunner::class)
class KotlinTest {
@Mock
private lateinit var jdbcTemplate: JdbcTemplate
@InjectMocks
private …
Run Code Online (Sandbox Code Playgroud) 我只是在kotlin的初级水平.我没有任何办法在kotlin中为数组添加值.我想从用户获取值并将它们添加到数组中.
val arr = arrayOf<Int>()
Run Code Online (Sandbox Code Playgroud)
要么
var arr = intArrayOf()
Run Code Online (Sandbox Code Playgroud)
像在Java中一样
Scanner ob=new Scanner(System.in);
int arr[]=new int[5];
for(int i=0;i<arr.length;i++)
{
arr[i]=ob.nextInt();
}
Run Code Online (Sandbox Code Playgroud)
如何在kotlin中执行相同的操作?
kotlin ×8
java ×5
arrays ×2
generics ×2
java-8 ×2
collections ×1
file ×1
filter ×1
function ×1
inheritance ×1
java-stream ×1
junit ×1
jvm ×1
mockito ×1
string ×1
try-catch ×1
unit-testing ×1