Collection map 연습
정수 리스트를 인자로 받아서 아래와 같이 새 리스트를 만들어서 리턴하는 함수를 작성하시오.
- 인자로 받은 리스트의 원소 중 홀수인 원소는 2배를 하고, 짝수인 원소는 그대로 사용하여 새 리스트를 만든다.
fun doubleOddNumbers(list: List<Int>): List<Int> {
// TODO: implement function
return list.map{ if(it%2!=0)it*2 else it}
}
fun main()
{
val testCases = listOf(
Pair(listOf(1, 2, 3, 4, 5), listOf(2, 2, 6, 4, 10)),
Pair(listOf(2, 4, 6, 8), listOf(2, 4, 6, 8)),
Pair(listOf(1, 3, 5, 7), listOf(2, 6, 10, 14))
)
for ((input, expectedOutput) in testCases) {
val actualOutput = doubleOddNumbers(input)
if (actualOutput != expectedOutput) {
println("Test failed for input $input. Expected output: $expectedOutput. Actual output: $actualOutput")
} else {
println("Test passed for input $input")
}
}
}
Scope 함수 연습
Person 객체를 만들고 속성을 지정하는 createPersonWith와 createPersonApply를 만드시오. 단, createPersonWith는 with scope 함수를 반드시 사용하고 createPersonApply는 apply 함수를 반드시 사용할 것.
class Person() {
var name: String? = null
var age: Int? = null
var email: String? = null
override fun toString() = "$name, $age, $email"
}
fun createPersonWith(_name: String, _age: Int, _email: String? = null): Person {
// TODO: implement function
return with(Person()) {
name=_name
age=_age
email=_email
this
}
}
fun createPersonApply(_name: String, _age: Int, _email: String? = null): Person {
// TODO: implement function
return Person().apply{
name=_name
age=_age
email=_email
}
}
fun main() {
val person1 = createPersonWith("Alice", 30)
println(person1) // expected output: Alice, 30, null
val person2 = createPersonApply("Bob", 25, "bob@example.com")
println(person2) // expected output: Bob, 25, bob@example.com
}
Snackbar 메시지 보여주기
따라하기 실습에서 println(“#### Hello, World ####”) 대신에 Snackbar 메시지를 보여주도록 만든다. Snackbar 메시지는 앱 하단에 아래 그림과 같이 표시되는 알림 메시지이다. Snackbar 메시지 표시하는 코드 참고:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle import android.widget.TextView
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
val txtView = findViewById(R.id.txtView)
txtView.setOnClickListener {
Snackbar.make(txtView, "이것은 Snackbar 입니다.", Snackbar.LENGTH_SHORT).show()
}
}
}