In Kotlin I have an enum as follows:
enum class MediaType() {
AUDIO,
VIDEO,
ARTICLE;
}
I would like to add either a function or some property that allows an enum member to be converted to some corresponding text. For example:
var mediaType = MediaType.AUDIO
var text = mediaType.toText() // returns the string "MP3"
mediaType = MediaType.VIDEO
text = mediaType.toText() // returns the string "mpeg"
While I can add the toText function to the MediaType class, I am not sure how that function references the value it is set to.
You can add a property to the enum...
enum class MediaType(val text: String) {
AUDIO("mp3"),
VIDEO("mpeg"),
ARTICLE("text");
}
And then use it like this:
println(MediaType.AUDIO.text)
If you'd like a toText() function rather than a property, that can be added as well, but probably isn't as idiomatic:
enum class MediaType(private val text: String) {
AUDIO("mp3"),
VIDEO("mpeg"),
ARTICLE("text");
fun toText(): String = text
}
Update:
Another way is to add an extension function and keep this logic outside the enum entirely:
fun MediaType.toText(): String =
when(this) {
MediaType.AUDIO -> "mp3"
MediaType.VIDEO -> "mpeg"
MediaType.ARTICLE -> "text"
}
enum class MediaType() {
AUDIO,
VIDEO,
ARTICLE;
fun getMemberText() = when (this) {
AUDIO -> "mp3"
VIDEO -> "mpeg"
else -> "text"
}
}
Related
I have multiple data classes and each class has a corresponding class containing more info. I want to write a function in which I should be able to pass an identifier (table name corresponding to the data class). Based on this identifier, object of the corresponding class should be made, the value changed and this object should be returned as output of the function. I have written a simplified version of it on playground but I am unable to get it to work. Any help is appreciated.
class someClass(
)
class objectForSomeClass(
var value: String
)
class someOtherClass(
)
class objectForSomeOtherClass(
var value: String
)
class doSomething() {
companion object {
val classMap = mapOf(
"someClass" to objectForSomeClass::class,
"someOtherClass" to objectForSomeOtherClass::class,
)
}
// Create a map of class name to a new object based on the class name input
fun dummyFun(className: String, valueInput: String): Map<String, kotlin.Any> {
var returnObject = mutableListOf<Pair<String, kotlin.Any>>()
when(className) {
"SOME_CLASS" -> {
returnObject = mutableListOf<Pair<String, justDoIt.classMap["someClass"]()>>()
}
"SOME_OTHER_CLASS" -> {
returnObject = Map<String, justDoIt.classMap["someOtherClass"]()>
}
}
returnObject[className].value = valueInput
return returnObject
}
}
fun main() {
var obj = doSomething()
var t = obj.dummyFun("SOME_CLASS", "Value to be inserted")
// do something with t
}
Not knowing more about your classes (the ones in your code are not data classes – a data class in Kotlin is a specific type of class) I still think a lot could be simplified down to maybe even this:
fun createObject(className: String, value: String): Any? {
return when (className) {
"SomeClass" -> ObjectForSomeClass(value)
"SomeOtherClass" -> ObjectForSomeOtherClass(value)
// ...
else -> null
}
}
Additionally:
The classMap is not necessary, you can hard-code the cases in the when clause as in my example. There is also no need for reflection, which you would need to create instances from SomeType::class.
With getting rid of classMap you also do not need the companion object holding it anymore, and then you are left with one function for creating instances of your classes, and this function does not have to be in a class. You might put it into a singleton class called object in Kotlin (https://kotlinlang.org/docs/object-declarations.html#object-expressions)
Data classes in Kotlin: https://kotlinlang.org/docs/data-classes.html
You could maybe also replace each class someClass & class objectForSomeClass pair with a class someClass with a companion object.
I have enum in swift
enum Type {
case bool(Bool)
case int(Int)
case array([String])
}
Dont understand how i can convert this to kotlin code, i did like this:
enum class AnswerSheetType {
BOOL,
INT,
ARRAY
}
But how i can pass variable to enum type. For example then i want create method which will be return type with variable, like this(swift code):
func marks(for id: String) -> Type {
let answer = answers?[id]
if let boolAnswer = answer as? Bool {
return .bool(boolAnswer)
}
if let intAnswer = answer as? Int {
return .int(intAnswer)
}
if let arrayAnswer = answer as? [String] {
return .array(arrayAnswer)
}
}
You can use a sealed interface/class to represent this.
sealed interface Type {
data class BoolType(val value: Bool) : Type
data class IntType(val value: Int) : Type
data class ArrayType(val value: Array<String>) : Type
// if you have a case that doesn't have any associated values, just use an object
// object CaseWithoutAssociatedValues: Type
}
Usage:
// let someType: Type = .bool(true)
val someType: Type = Type.BoolType(true)
// just like how you can use a switch on a Swift enum, you can use a when like this too:
// This when is also exhaustive, if you specify all the implementers of Type
when (someType) {
is Type.BoolType -> println("Bool value: ${someType.value}")
is Type.IntType -> println("Int value: ${someType.value}")
is Type.ArrayType -> println("Array value: ${someType.value}")
}
Notice that in each of the branches, you can access someType.value, because of the smart-cast. This is unlike in Swift, where you would do pattern matching to get the associated values out.
As I was writing my answer Sweeper already answered with almost the identical solution. I wanted to add to that, that your marks function could then be written as this:
fun marks(id: String) : Type? {
when (val answer = answers?.get(id)) {
is Boolean -> return Type.BoolType(answer)
is Int -> return Type.IntType(answer)
is Array<*> -> if (answer.isArrayOf<String>()) return Type.ArrayType(answer as Array<String>)
}
return null
}
The Array case is a bit ugly but that is because checking on is Array<String> is not possible. The IDE will also still complain about having an unchecked cast but it should work. I don't know if there's a nicer way to handle this.
I'm fetching json that has a 'type' field that contains a string, and I want to store this in my model object as an Enum with a string value.
The API I'm working with doesn't return all the information in one fetch, so once I have all the data I call my setProperties method.
All of my primitives are stored correctly in memory & my room db, but my Type class isn't converted. Any idea whats wrong with my type converter?
// Enum
enum class Type(var value: String) {
ARTICLE("article"),
COMMENT("comment"),
UNKNOWN("unknown")
}
// data class
data class FeedItem(#PrimaryKey override var id: Int) : Item(id) {
#TypeConverters(TypeConverter::class)
var type: Type? = Type.UNKNOWN
// other props...
fun setProperties(itemToCopy: FeedItem) {
this.type = itemToCopy.type
// set other props
}
}
// TypeConverter
class TypeConverter {
#TypeConverter
fun toString(type: Type?): String? {
return type?.value
}
#TypeConverter
fun toType(value: String?): Type? {
return when(value) {
Type.ARTICLE.value ->Type.ARTICLE
Type.COMMENT.value -> Type.COMMENT
else -> Type.UNKNOWN
}
}
}
I'm new to Kotlin, so I have this interface.
interface User {
var nickName : String
}
Now I want to create a class PrivateUser that implements this interface. I have also to implement the abstract member nickName.
Via constructor it's very simple
class PrivateUser(override var nickName: String) : User
However when I try to implement member inside the class Idea generates me this code
class Button: User {
override var nickName: String
get() = TODO("not implemented")
set(value) {}
}
It's confusing to me how to implement it further.
Properties must be initialized in Kotlin. When you declare the property in the constructor, it gets initialized with whatever you pass in. If you declare it in the body, you need to define it yourself, either with a default value, or parsed from other properties.
Some examples:
class Button : User {
override var nickname = "Fred"
}
class Button(val firstName: String, val lastName: String) : User {
override var nickname = "${firstname[0]}$lastname"
}
The code generated by IDEA is useful if you want a non-default getter and/or setter, or if you want a property without a backing field (it's getter and setter calculate on the fly when accessed).
More examples:
class Button : User {
override var nickname = "Fred"
get() = if (field.isEmpty()) "N/A" else field
set(value) {
// No Tommy
field = if (value == "Tommy") "" else value
}
}
class Button(val number: Int) : User {
var id = "$number"
private set
override var nickname: String
get() {
val parts = id.split('-')
return if (parts.size > 1) parts[0] else ""
}
set(value) {
field = if (value.isEmpty()) "$number" else "$value-$number"
}
}
I have a question about typescript properties: Is it possible to get the setter and getter of a typescript property or to declare a function argument to be of a property of X type?
The reason is to get some sort of "reference" to a variable which is not possible in plain JS without writing getter/setter wrappers or access the variable via parent object itself (obj["varname"]).
For example (with some working code and other parts speculative):
//A sample class with a property
class DataClass<T> {
private T val;
public get value(): T {
return this.val;
}
public set value(value: T) {
this.val = value;
}
}
//Different ways of modifing a member "by reference"
class ModifyRef {
public static void DoSomethingByGetterAndSetter(getter: () => string, setter: (val: string) => void) {
var oldValue = getter();
setter("new value by DoSomethingByGetterAndSetter");
}
public static void DoSomethingByObject(obj: Object, name: string) {
var oldValue = obj[name];
obj[name] = "new value by DoSomethingByObject";
}
//Is something like this possible?
public static void DoSomethingByProperty(somePropery: property<string>) {
var oldVlaue = someProperty;
someProperty = "new value by DoSomethingByProperty";
}
}
var inst = new DataClass<string>();
//Calling the DoSomethingByProperty if possible
ModifyRef.DoSomethingByProperty(inst.value);
//Or if not is something like this possible
ModifyRef.DoSomethingByGetterAndSetter(inst.value.get, inst.value.set);
The simplest way to do this would be to provide methods, rather than a property:
//A sample class with a property
class DataClass<T> {
private val: T;
public getValue(): T {
return this.val;
}
public setValue(value: T) {
this.val = value;
}
}
class ModifyRef {
public static DoSomethingByGetterAndSetter(getter: () => string, setter: (val: string) => void) {
var oldValue = getter();
setter("new value by DoSomethingByGetterAndSetter");
}
}
var inst = new DataClass<string>();
//Or if not is something like this possible
ModifyRef.DoSomethingByGetterAndSetter(inst.getValue, inst.setValue);
I've long found it very surprising that languages with properties don't include a convenient way to make a reference to a property, and have daydreamed about having this feature in C#. It ought to work on local variables as well.
A popular pattern for this kind of first-class or reified property is a single function that can be called in two ways:
no arguments: returns current value.
one argument: sets value, returns undefined.
Or in TypeScript terms:
interface Property<T> {
(): T;
(newVal: T): void;
}
The methods of jQuery objects often work like this. An example of this pattern in modelling pure data is in Knockout, in which such properties also support change subscriptions, and there's a rather elegant pattern for defining computed properties that automatically recompute when their dependencies change.