https://www.baeldung.com/kotlin-sealed-classes
Sealed Classes in Kotlin
.
.
.
.
https://youtu.be/o1Occux4qR8
.
.
.
.
https://youtu.be/o1Occux4qR8./
.
.
.
.
https://www.charlezz.com/?p=43886
.
.
.
.
Enumerations in Kotlin are data types that hold a set of constants. Enums are defined by adding the modifier enum
in front of a class as shown below. Yes, in Kotlin, Enums are classes.
enum class Months{
January,
February,
March
}
Here are some important points about enum classes in kotlin.
Let’s see how the enum class is initialized in the main
function of our class.
fun main(args: Array<String>) {
println(Months.January) //prints January
println(Months.values().size) //prints 3
println(Months.valueOf("March")) //prints March
for (enum in Months.values()) {
println(enum.name)
}
println(Months.valueOf("Mar")) //throws java.lang.IllegalArgumentException: No enum constant Months.Mar
}
Few inferences from the above code:
Let’s see how to tackle this scenario.
fun enumContains(name: String): Boolean {
return enumValues<Months>().any { it.name == name }
}
fun main(args: Array<String>) {
if (enumContains("")) {
println(Months.valueOf(""))
} else {
println("The string value does not match with any of the enum constants.") //this gets printed.
}
}
enumContains
is a function that calls the lambda function any which iterates over the enum constants to check if any of them matches the string and returns a boolean.
Enum Properties
Every enum constant has properties: name
, ordinal
to retrieve the name and position of the constant.
fun main(args: Array<String>) {
println(Months.January.name) //prints January
println(Months.March.ordinal) // prints 2
for (enum in Months.values()) {
println(enum.name)
}
}
Enum toString()
We can override the toString() function in the enum class as shown below.
enum class Months {
January,
February,
March;
override fun toString(): String {
return super.toString().toUpperCase()
}
}
fun main(args: Array<String>) {
println(Months.January) //prints JANUARY
println(Months.January.name) //prints January
println(Months.valueOf("March")) //prints MARCH
}
Enums are classes. So besides defining the constants we can define other things as well that can be present in a class. To do so we need to first end the enum part with a semi colon.
Note: Month.January
invokes the toString()
method of the class whereas Month.January.name
directly prints the enum constant’s name.
Enum Initialisation
Enum constants can be initialized using primary constructors as shown below.
enum class Months(var shorthand: String) {
January("JAN"),
February("FEB"),
March("MAR");
}
fun main(args: Array<String>) {
var x = Months.January
println(x.shorthand) //prints JAN
x.shorthand = "Shorthand changed to J."
println(Months.January.shorthand) //prints Shorthand changed to J.
}
Enums as Anonymous classes
Enum constants can behave as anonymous classes be implementing their own functions along with overriding base functions from the class as shown below.
enum class Months(var shorthand: String) {
January("JAN"){
override fun printSomething() {
println("First month of the year.")
}
},
February("FEB"){
override fun printSomething() {
println("Second month of the year.")
}
},
March("MAR"){
override fun printSomething() {
println("Third month of the year.")
}
};
var a: String = "Hello, Kotlin Enums"
abstract fun printSomething()
}
fun main(args: Array<String>) {
Months.February.printSomething() //prints Second month of the year.
println(Months.February.a) //prints Hello, Kotlin Enums
}
Each of the enum constants must override
Enum inside an Enum
It’s possible to define another enum class in the current enum class as shown below.
enum class Months {
January,
February,
March;
enum class Day{
Monday,
Tuesday,
Wednesday
}
}
fun main(args: Array<String>) {
println(Months.Day.Tuesday) //prints Tuesday
}
Only an enum class can invoke another one. The inner class Day
cannot be invoked from the enum constants.
Enums and when
when
is Kotlin equivalent of switch in Java. We’ve covered the workings of it in the Control Flow tutorial.
An example showing how when statements are used with enums is given below.
enum class Months {
January,
February,
March;
}
fun main(args: Array<String>) {
var m = Months.February
when (m) {
Months.January -> print("Matches with Jan")
Months.February -> print("Matches with Feb") //prints this.
Months.March -> print("Matches with Mar")
}
}
This brings an end to kotlin enum tutorial.
References: Kotlin Docs
.
.
.
.
.
.
.
enum class
.
.
.
.
.
.
.
.
.
.
sealed class의 경우 parent constructor가 정의되어있지 않더라도 child class 는 constructor를 가질수 있다. 각 class 정의 사이에 구분자는 없다. (정의부분 뒤에 enum의 경우 , 가 붙는데 sealed class의 경우는 없다는 이야기)
sealed class BasicGarment2(){
class CLEAN_PRESS(var name:String, var price:BigDecimal): BasicGarment2()
class CLEAN_ONLY(): BasicGarment2()
}
enum class BasicGarment(val na: String, val price:BigDecimal){
CLEAN_PRESS("a",10.toBigDecimal()){
override fun calculatePrice(): BigDecimal {
return 10.toBigDecimal()
}
fun foo(){
println("test func")
}
override var testVar: String
get() = TODO("Not yet implemented")
set(value) {}
},
CLEAN_ONLY("nam", 10.toBigDecimal()){
override fun calculatePrice(): BigDecimal {
return 10.toBigDecimal()
}
override var testVar: String
get() = TODO("Not yet implemented")
set(value) {}
};
abstract fun calculatePrice():BigDecimal
abstract var testVar :String
}
.
.
.
.
Swift Typealias: How to use them and Why?
A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program.
Type alias do not create new types. They simply provide a new name to an existing type.
The main purpose of typealias
is to make our code more readable, and clearer in context for human understanding.
It is declared using the keyword typealias
as:
typealias name = existing type
In Swift, you can use typealias
for most types. They can be either:
You can use typealias for all built in data Types as String, Int, Float etc.
For example:
typealias StudentName = String
The above declaration allows StudentName to be used everywhere instead of String
. So, if you want to create a constant of type string but represents more like student name. You can do as:
let name:StudentName = "Jack"
Without using typealias, you should declare constant of type string as:
let name:String = "Jack"
Above both examples creates a constant of type String
. But declaring with typealias
, our code becomes more readable.
There are many cases when you need to create your own data type. Suppose you want to create a Type that represents Student, you can create it using a class as:
class Student {
}
Now a group of students can be represented as an array as:
var students:Array<Student> = []
The above declaration can be made more readable by creating your own type for Array<Student>
using typealias
as:
typealias Students = Array<Student>
Now we can make our code more readable as:
var students:Students = []
Lets analyze one more example. Suppose we have a method that takes a closure as an input parameter.
Don’t worry if you do not know about closures. Just think of it as a special type of function. We have explained it detail in the article: Swift closures.
func someMethod(oncomp:(Int)->(String)){
}
The above example takes a closure as an input to someMethod
. The closure takes an Int
value and returns String
.
You can see the use of (Int)->(String)
makes less sense to the reader. You can use typealias
to provide a new name for it:
typealias CompletionHandler = (Int)->(String)
Now you can rewrite the method as:
func someMethod(oncomp:CompletionHandler){
}
We can see the same code looks more clear and programmer friendly with the use of typealias
.
Swift: Understanding Mutating Functions in Two Minutes
If you have ever tried using the mutating keyword in your class methods in Swift, the compiler will definitely yell at you because you are doing something wrong.
In swift, classes are reference type whereas structures and enumerations are value types. The properties of value types cannot be modified within its instance methods by default. In order to modify the properties of a value type, you have to use the mutating keyword in the instance method. With this keyword, your method can then have the ability to mutate the values of the properties and write it back to the original structure when the method implementation ends.
Below is a simple implementation of Stack in Swift that illustrates the use of mutating functions.
struct Stack { public private(set) var items = [Int]() // Empty items array mutating func push(_ item: Int) { items.append(item) } mutating func pop() -> Int? { if !items.isEmpty { return items.removeLast() } return nil } } var stack = Stack() stack.push(4) stack.push(78) stack.items // [4, 78] stack.pop() stack.items // [4]
I believe this is pretty straight forward to understand. If, however you need any clarification or questions, leave me a comment below and I will get it answered. Thanks for reading.
https://youtu.be/VNEdufXVMaU6 1 What is Text Classification
https://youtu.be/kxImnFg4ZiQ
6 2 Naive Bayes
https://youtu.be/j39c7Gjx2gE
감마 기호는 function을 의미한다.
6 3 Formalizing the Naive Bayes Classifier
d 는 document, c는 class를 의미한다.
P(d|c) 는 likelihood probability, P© prior probability
documents는 x features (단어들)의 연속으로 구성되어있다.
P(x1, x2, x3 ……. xn | c)의 경우 conditional 에 conditional에 중첩된 conditional probability 계산이 되는데 이런경우 복잡해지게 된다.
계산이 복잡해지는데 이를 간소화 시켜서 계산하는 방법을 사용한다. bag of words를 이용하거나 independent probability를 이용(모든 단어는 서로 independent하다고 가정)한다.
6 4 Naive Bayes Learning
https://youtu.be/3jR8TZG8T88
P(cj)는 전체 문서에서 특정 class의 문서가 나올 확률이다.
P(wi | cj)는 특정 class에서 특정 word가 나올 확률이다.
위의 내용을 간단히 정리하면 특정 class의 모든 문서(시그마부분에 해당)를 하나로 만들고 그 안에서 특정단어들이 나오는 횟수를 이용해 P(wi | cj)를 구한다.
training documents에 fantastic이라는 단어가 한번도 사용되지 않았다. 그런데 새로 주어진 문장에서는 이 단어가 사용되었다고 한다면 이전에는 한번도 나온적이 없었으므로 확률이 0이 되버리게 된다. 즉 새로운 단어에 대한 고려가 전혀 없는 것이다. 이 문제의 해결방법은 아래 그림 참조
모든 단어의 출현횟수를 1씩 늘려줌으로써 최소횟수가 0이 아닌 1이 되게된다.
우측 하단은 add alpha가 적용된 공식이다.
training doc에서 한번도 출현하지 않은 단어는 unknown word로 위와 같이 처리한다.
6 5 Naive Bayes Relationship to Language Modeling
https://youtu.be/LRFdF9J__Tc
6 6 Multinomial Naive Bayes A Worked Example
https://youtu.be/OWGVQfuvNMk
P©는 전체 문서들중에 class c 문서가 나올 확률이다. 여기서 사용된 P(w | c)는 add one smoothing이 적용된 특정 class에서 특정 단어들이 나올 확률이다.
위의 예제는 주어진 training data를 이용해 만든 모델로 test doc의 class를 예상하는 과정이다. 오른쪽 하단의 내용은 주어진 문서 d5가 어떤 클래스인지를 비교 추측하는 것이다. 각 c , j class일 확률을 비교 한다. 이때 d5는 공통으로 들어가는 부분이므로 생략했다.
6 7 Precision, Recall, and the F measure
https://youtu.be/81j2nzzBHUw
참조자료)
andrew ng https://youtu.be/wGw6R8AbcuI
위그림이 좀더 이해하기 쉽다.
accuracy 측정 방법
6 8 Text Classification Evaluation
https://youtu.be/TdkWIxGoiak
6 9 Practical Issues in Text Classification
https://youtu.be/uIvSHmsLs-U
text classification에 대한 전반적인 내용을 다루고 있다.
training data가 없는 경우 개발자가 직접 손수 rule을 만든다.
knn k nearest neighbors를 말한다.
보통 training data의 양이 많은 경우 classifier간의 성능차는 별로 없어지게 된다.
자동, 수동 섞어서 처리한다.
확률의 곱이 많이 이어지는 경우 그 숫자가 매우 작아지는 경우가 생기는데 이를 underflow라고 한다. 이를 방지 하기 위해 log값을 이용한다. log에서는 두 값이 곱이 합으로 계산되기 때문이다.
upweighting : 단어의 위치나 사용방법에 따라 가중치를 두는 방법이다.
How to get names of classes inside a jar file?
original source : https://stackoverflow.com/questions/15720822/how-to-get-names-of-classes-inside-a-jar-file
jar file 내에 class 내용 확인 하는 방법
You can use Java jar
tool. List the content of jar file in a txt file and you can see all the classes in the jar.
jar tvf jarfile.jar