kotlin Kotlin类和对象

Kotlin类和对象

classes_and_objects_one.kt
fun main(args: Array<String>) {
    val primary = Primary("Doe")
    val primaryCon = PrimaryConstructor("John")
    primary.testCall()
    primaryCon.testCall()
}

class Primary constructor(val firstName: String) {
    fun testCall() {
        println("First Name : $firstName")
    }
} 

class PrimaryConstructor(val firstName: String) {
    fun testCall() {
        println("First Name : $firstName")
    }
}

kotlin 空检查1

空检查1

null_check_one.kt
var testString: String? = "How are you"
testString = null
if (testString == null) {
    println("testString is null")
}
testString = "How do you do?"
if(testString == null) {
    println("testString is null")
} else {
    println("testString is not null")
}

kotlin 对于Loop Kotlin

对于Loop Kotlin

kotlin_for.kt
val myLists = listOf("Sun", "Mon", "Tue", "Wed", "Thu", "Fri")
val myArray = arrayOf("Aung Aung", "Maung Maung", "Kaung Kaung", "Hlaung Hlaung")
for (myList in myLists) {
    println(myList)
}
for (i in myArray.indices) {
    println(myArray[i])
}

kotlin Kotlin发表声明

Kotlin发表声明

kotlin_when.kt
class Test {
    fun test() {
        val x = 1
        when(x) {
            1 -> println("One")
            2 -> println("Two")
            else -> {
                println("Others")
            }
        }

        val y = 4
        when (y) {
            in 1..5 -> println("It's in the range of 1 to 5")
            !in 7..9 -> println("It's not in the range of 7 to 9")
            6 -> println("Six")
            else -> {
                println("Others")
            }
        }

        when {
            x.isOdd() -> println("X is Odd")
            x.isEven() -> println("X is Even")
        }
    }
}

private fun Int.isEven(): Boolean {
    if(this % 2 != 0) {
        return true
    }
    return false
}

private fun Int.isOdd(): Boolean {
    if( this % 2 == 0) {
        return true
    }
    return false
}

kotlin Kotlin IF声明

Kotlin IF声明

if_statement.kt
val numOne = 45
val numTwo = 34
val max = if (numOne > numTwo) numOne else numTwo
println(max)

val anotherMax = if(numOne > numTwo) {
    print("A is Max")
    numOne
} else {
    print("B is Max")
    numTwo
}

println(anotherMax)

kotlin 对于循环斐波那契

由科特林

Fibonacci.kt
import java.math.BigInteger

fun fibonacci(num: Int): BigInteger {
  var cnt = 0
  var first : BigInteger = BigInteger.ZERO
  var second : BigInteger = BigInteger.ONE
  var theSum : BigInteger = BigInteger.ZERO
  while (cnt <= num){
    theSum = first.add(second)
    first = second
    second = theSum
    cnt++
  }
  return theSum
}

fun main(args: Array<String>) {
  println(fibonacci(8180))
}

kotlin Android Gps更新

MainGpsActivity.kt
class MainActivity : AppCompatActivity() {

    lateinit var fusedClient: FusedLocationProviderClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // this is awful!
        instance = this

        Dexter.withActivity(this)
            .withPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
            .withListener(object: PermissionListener{
                override fun onPermissionGranted(response: PermissionGrantedResponse?) {
                    updateLocation()
                }

                override fun onPermissionRationaleShouldBeShown(
                    permission: PermissionRequest?,
                    token: PermissionToken?
                ) {
                    Toast.makeText(this@MainActivity, "Please grand location permission", Toast.LENGTH_SHORT).show()
                }

                override fun onPermissionDenied(response: PermissionDeniedResponse?) {
                    Toast.makeText(this@MainActivity, "Please grand location permission", Toast.LENGTH_SHORT).show()
                }
            }).check()
    }

    private fun updateLocation() {
        fusedClient = LocationServices.getFusedLocationProviderClient(this)
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return
        }
        fusedClient.requestLocationUpdates(buildLocationRequest(), getPendingIntent())
    }

    private fun getPendingIntent(): PendingIntent? {
        val intent = Intent(this, LocationReceiver::class.java)
        intent.action = LocationReceiver.ACTION_PROCESS_UPDATE
        return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
    }

    private fun buildLocationRequest() = LocationRequest().apply {
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
            interval = UPDATES_INTERVAL
            fastestInterval = FASTEST_INTERVAL
            smallestDisplacement = SMALLEST_DISPLACEMENT
    }

    fun updateTextView(locationString: String) {

    }

    companion object {

        const val UPDATES_INTERVAL = 5 * 1000L
        const val FASTEST_INTERVAL = 2 * 1000L
        const val SMALLEST_DISPLACEMENT = 10f

        var instance: MainActivity? = null
    }
}
LocationReceiver.kt
class LocationReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        val action: String? = intent?.action
        if (ACTION_PROCESS_UPDATE == action) {
            val result: LocationResult? = LocationResult.extractResult(intent)
            val location: Location? = result?.lastLocation
            val locationString = "${location?.latitude}/${location?.longitude}"
            try {
                MainActivity.instance?.updateTextView(locationString)
            } catch (e: Exception) {
                Toast.makeText(context, "$e, locationString", Toast.LENGTH_SHORT).show()
            }
        }

    }

    companion object {
        const val ACTION_PROCESS_UPDATE = "com.agforce.gps.UPDATE_LOCATION"
    }
}

kotlin ffmpeg来自dir与图像

给出一个带编号文件的文件夹<br/> <br/>``` <br/> ./R1_235_CC <br/> ./R1_235_CC/M99_R1.086208.tif <br/> ./R1_235_CC/M99_R1.086209.tif <br/> ./R1_235_CC/M99_R1.086210.tif <br/> ./R1_235_CC/M99_R1.086211.tif <br/>``` <br/>生成ffmpeg输入命令<br/>``` <br/> ffmpeg -f image2 -start_number 086208 -i'./R1_235_CC/M99_R1.%06d.tif'<br/>```

dpxls.kts
import java.io.File
import java.io.FileFilter
import java.text.ParseException

val MEDIASEQ_UNKNOWN = -1

fun getMediaSequence(f: File) = getMediaSequence(f.name)

fun getMediaSequence(s: String): Int {
    if (s.startsWith(".")) return MEDIASEQ_UNKNOWN
    val basename = getBaseName(s)
    val split = basename.split("[^0-9]+".toRegex())
    return split.lastOrNull()?.toIntOrNull() ?: MEDIASEQ_UNKNOWN
}

fun getDirMediaSequence(dir: File, filter: FileFilter? = null): Int {
    return dir.listFiles(filter).orEmpty().map { getMediaSequence(it) }.max() ?: MEDIASEQ_UNKNOWN
}

val MEDIASEQ_CMP = Comparator { o1: File, o2: File -> getMediaSequence(o1) - getMediaSequence(o2) }

val MEDIASEQ_CMPString = Comparator { o1: String, o2: String -> getMediaSequence(o1) - getMediaSequence(o2) }

fun getBaseName(filename: String) =  filename.substringAfterLast("/").substringBeforeLast(".")

fun dpxInfoFromFile(f: File): DpxFilename {
    // simple - 0177670.dpx
    // vdms - Scrubs_Ep101_102_CR_B019_1641738.dpx
    // cbs - BX505_SR7378_01.00089437.dpx

    val bn = getBaseName(f.name)
    var number = ""
    var reel: String? = ""
    for (i in bn.length - 1 downTo 0) {
        val c = bn[i]
        if (Character.isDigit(c)) {
            number = c + number
        } else {
            reel = bn.substring(0, i)
            break
        }
    }

    if (number.isNotBlank()) {
        val pf = f.parentFile
        var clip: String? = pf?.name
        if ((clip ?: "").matches("[0-9]+x[0-9]+".toRegex())) {
            //CBS weird corner case: /$CLIP/$videoRes/*.dpx
            clip = f.parentFile.parentFile.name
        }
        reel = if (reel.isNullOrBlank()) null else reel
        val filenamesPattern = f.name.replace(number, "%0${number.length}d")
        return DpxFilename(clip, reel, number, filenamesPattern)
    }
    throw ParseException("Can't parse filename ${f.absolutePath}", 0)
}

fun dpxInfoFromFiles(url: String, dpxList: List<File>): DpxFilename {
    val dpxls = dpxList.sortedWith(MEDIASEQ_CMP)
    val firstDpx = dpxls.firstOrNull() ?: throw IllegalStateException("No dpx files found at URL $url")
    val lastDpx = dpxls.lastOrNull() ?: throw IllegalStateException("No dpx files found at URL $url")

    val dpxinfo1 = dpxInfoFromFile(firstDpx)
    val dpxinfo2 = dpxInfoFromFile(lastDpx)

    if (dpxinfo1.filenamesPattern == dpxinfo2.filenamesPattern) {
        return dpxinfo1
    }
    if (dpxinfo1.number.startsWith("0") || dpxinfo2.number.startsWith("0")) {
        throw IllegalStateException("cant create dpx number pattern ${firstDpx.name} vs ${lastDpx.name}")
    }

    val filenamesPattern = firstDpx.name.replace("${Integer.parseInt(dpxinfo1.number)}", "%d")
    return DpxFilename(dpxinfo1.clipName, dpxinfo1.reel, dpxinfo1.number, filenamesPattern)
}

data class DpxFilename(val clipName: String? // Usually it is DPX folder
                       , val reel: String? // Usually is it part of the dpx filename
                       , val number: String, val filenamesPattern: String)


args.forEach {
    val f = File(it)
    when {
        f.isDirectory -> {
            val files = f.listFiles().orEmpty()
            val jpgs = files.filter { ff -> ff.name.toLowerCase().endsWith("jpg") }
            val pngs = files.filter { ff -> ff.name.toLowerCase().endsWith("png") }
            val dpxs = files.filter { ff -> ff.name.toLowerCase().endsWith("dpx") }
            val tifs = files.filter { ff -> ff.name.toLowerCase().endsWith("tif") }

            val ls = arrayOf(jpgs, pngs, dpxs, tifs).maxBy { ff -> ff.size } ?: emptyList()
            val info = dpxInfoFromFiles(it, ls)
            println("ffmpeg -f image2 -start_number ${info.number} -i '$it/${info.filenamesPattern}'")
        }
        f.isFile -> {
            println(dpxInfoFromFile(f))
        }
    }
}

kotlin 什么时候

when
when (x) {
  1 -> print("x == 1")
  2 -> print("x == 2")
  else -> { // Note the block
    print("x is neither 1 nor 2")
  }
}

kotlin MapToString,反之亦然

mapToString.kt
fun mapToString(map: Map<String, String>): String {
    val arrayOfMapEntries = map.entries.map { entry ->
        entry.key + "=" + entry.value
    }
    return arrayOfMapEntries.joinToString(",")
}
stringToMap.kt
fun stringToMap(s: String): Map<String, String> {
    val map = s.split(",").associate {
        val (left, right) = it.split("=")
        left to right
    }
    return map
}